简体   繁体   中英

SQL Select issue with PHP

My site is successfully inserting date from values the user has entered, however, when it comes to getting data from the database I have a problem.

Here's my code:

$sql = "SELECT cost FROM settings LIMIT 1";
if ($conn->query($sql) === TRUE) 
{
    $cost = $sql;
} 
else 
{
    echo "Error: " . $sql . "<br>" . $conn->error;
} 

I'm just getting an error (Error: SELECT cost FROM settings LIMIT 1) and I'm unsure how to identify the problem. Everything looks correct from my point of view, obviously it's not.

Try using backtics,

$sql = "SELECT `cost` FROM `settings` LIMIT 1";

And also,

if ($sql->num_rows > 0) {
    .....

Actually the error is in. if ($conn->query($sql) === TRUE) { }

$conn->query($sql) will not return TRUE for SELECT QUERY ,it will return a result object. So the condition becomes false and you are getting the else part printed.

Try this code. This code works only if you have properly connected to DB.

$sql = "SELECT `cost` FROM `settings` LIMIT 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["cost"];
    }
} else {
    echo "0 results";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM