简体   繁体   中英

Errors in query to database with mysqli

something here is wrong but I can't find it. Plz help.

And I have a question: Why should we close the connection in the end? Is it a necessity?

$conn = new mysqli($dbConfig['DB_HOST'], $dbConfig['DB_USER'], $dbConfig['DB_PASSWORD'], $dbConfig['DB_NAME']);

if ($conn->connect_errno) {
    $errstr = printf("connection has been failed: %s", $conn->connect_error);
    echo $errstr;
    exit();
}

printf("you are connected to the <b><i>%s</i></b> database successfully.<br>", $dbConfig['DB_NAME']);

$result = $conn->prepare("select * from customers");
if (!$result) 
    printf('errno: %d, error: %s', $result->errno, $result->error);

$b = $result -> execute();
if (!$b) 
    echo "execute dosn't work";

$rows = $result->fetch_array(1);
printf("Name is: %s\n <br>",$rows['name']);

The code has updated!

  1. You can't bind tables or column names. For that you need to use a whitelist.
  2. You do not need to sanitize data in a prepared statement IF you parameterize (like you had done with the table name) the query. Prepared statements have no difference if they aren't parameterized.

The current issue is that you need to get the result, http://php.net/manual/en/mysqli-stmt.get-result.php .

so the end of your code should be:

$b = $result->execute();
if (!$b) 
    echo "execute dosn't work";
$result2 = $result->get_result();
$rows = $result2->fetch_array();

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