php mysqli插入变量查询 [英] php mysqli insert variables query

查看:203
本文介绍了php mysqli插入变量查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,这是问题所在.我正在尝试将变量插入到预定义的查询中.但是,它不起作用.如果我只是给它一个值,查询就可以工作,但是当我向其中插入变量时,查询将失败.帮助吗?

Ok so here is the question. I am trying to insert a variable into my query that is pre-defined. However it is not working. The query works if I just give it a value, but when I insert a variable into it, it fails. help?

$connection = new mysqli('localhost', 'user', 'pass', 'db'); 

$username = "test";

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $connection->query("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES ('".$username."', 'test', 'test', 'test', 'test', 'test')")){

  echo "success";
  $result->close();

}
else {
  echo "error";
}

$connection->close();
?>

如果我将$ username替换为任何值,它将起作用..我在这里丢失了什么吗?

If I replace $username with any value, it works.. Am I missing something here?

推荐答案

您好,适用于可能仍需要完成原始问题要求的任何人.

Hello this is for anyone who might still need accomplish what was asked in original question.

某人可能不想使用准备好的语句的原因-来自: http://www.php.net/manual/en/mysqli.quickstart.statements.php

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;

干杯!

这篇关于php mysqli插入变量查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆