Domanda

I am trying to INSERT data into a table from a form using MySQLi. I have my database connection on a separate include file before including the form that will INSERT the data. my connection looks like so:

@$DB = new mysqli($mysqlHost,$mysqlUser,$mysqlPass,$mysqlDB);
if($DB ->connect_errno >0){
    echo 'Could not connect to the server at this time. Please try again later.';
    exit;
}

Now i want to execute a query that will store the users information into a table called users. When i run the query in phpMyAdmin it works fine, so i'm guessing its something to do with the syntax or my logic. Here is my insert code:

if($stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')")){
     $stmt->execute();
     $stmt->close();
}
echo 'Data INSERTED INTO table.';

Here is the error i am receiving:

Warning: mysqli::prepare(): Couldn't fetch mysqli in C:\xampp\htdocs\Phpclass\Website\includes\register.php

If you need additional information please let me know, i have been working on this for sometime now and it is very frustrated.

È stato utile?

Soluzione

Change

$stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')");

To

if ($stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES (?, ?)"))
{
    $stmt->bind_param("ss", 'value1', 'value2');
    $stmt->execute();
    $stmt->close();
}

You have you bind the parameters if you use prepared statements. Prepared statements can be used to re-use an SQL query repetitively, to import large chunks of data.

If you're not requiring to import large chunks of data I would recommend using the following instead:

$q = $DB->query("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')");

Altri suggerimenti

You need to remove @ before $DB, also check error like below ;

$DB = @new mysqli($mysqlHost,$mysqlUser,$mysqlPass,$mysqlDB);
if($DB->connect_errno){
    echo 'Could not connect to the server at this time. Please try again later.';
    exit;
}

$stmt = $DB->prepare("INSERT INTO `users`(`email`, `password`) VALUES ('value1', 'value2')")
if ($stmt === FALSE) {
    die($DB->error);
}
$stmt->execute();
$stmt->close();
$DB->close();
echo 'Data INSERTED INTO table.';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top