php mysqli insert variables query
This question already has an answer here:
Hello this is for anyone who might still need accomplish what was asked in original question.
A reason why someone possibly might want to not use prepared statements--from: http://www.php.net/manual/en/mysqli.quickstart.statements.php
"Using a prepared statement is not always the most efficient way of executing a statement. A prepared statement executed only once causes more client-server round-trips than a non-prepared statement."
//you will want to clean variables properly before inserting into db
$username = "MyName";
$password = "hashedPasswordc5Uj$3s";
$q = "INSERT INTO `users`(`username`, `password`) VALUES ('".$username."', '".$password."')";
if (!$dbc->query($q)) {
echo "INSERT failed: (" . $dbc->errno . ") " . $dbc->error;
}
echo "Newest user id = ",$dbc->insert_id;
Cheers!
Since ther was some discussion above i thought id provide the following examples in pdo and mysqli for comparison:
MySQLi :
$connection = new mysqli('localhost', 'user', 'pass', 'db');
$username = "test";
if ($connection->errno) {
printf("Connect failed: %sn", $connection->error);
exit();
}
$username = 'test';
$stmt = $connection->prepare("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES (?,'test', 'test', 'test', 'test', 'test')");
$stmt->bind_param('s', $username_value);
$username_value = $username; // not we could simply define $username_value = 'test' here
if ($result = $stmt->execute()){
echo "success";
$stmt->free_result();
}
else {
echo "error";
}
$connection->close();
PDO :
try {
$db = new PDO($dsn, $user, $pass);
$username = 'test';
$stmt = $db->prepare("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES (?,'test', 'test', 'test', 'test', 'test')");
$stmt->execute(array($username));
echo 'Success';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
In this case, looking at the context of your question it is better to assign the username variable with some data like $username=$_POST['username'];
This might help...otherwise avoid the double quotes and simply put down $username
上一篇: LIKE运算符的MySQL注入
下一篇: php mysqli插入变量查询