我有一个像这样设置的mysqli数据库表
ID --- ---电子邮件密码。
我想要做的是在这里插入一行新信息。这就是我尝试过的:
编辑:这就是我连接数据库的方式,将连接保存在全局变量中:
global $db;
$db = new mysqli( 'localhost', 'username', 'password', 'database' );
if ( $db->connect_errno > 0 ) {
die( 'Unable to connect to database [' . $db->connect_error . ']' );
}
function juice_sign_up( $email, $password, $password_confirm )
{
global $db;
$emailCheck = 'SELECT email FROM user WHERE email = $email';
if($emailCheck == 'NULL'){
$hashPass = password_hash($password);
INSERT INTO user VALUES ($email, $hashPassword);
}
这是该函数获取变量的地方:
if( isset($_POST('password_confirm'))){
juice_sign_up($_POST['email'], $_POST['password'], $_POST['password_confirm']);
}
我是使用MYSQL的新手,还没有完全理解语法。任何帮助表示赞赏。
答案 0 :(得分:1)
这里有一些问题。您不执行选择查询(您只是构建字符串)。并且插入语句就好像它是PHP代码一样,但这不是你执行语句的方式。此外,您至少需要将输入转义为insert语句,或者甚至使用参数绑定。
要执行查询,您可以使用mysqli->query。它返回一个查询结果对象(用于选择查询)或true
(用于DML语句)。如果发生错误,它会返回false
。
我在以下代码段的注释中解决了这些问题:
function juice_sign_up( $email, $password, $password_confirm )
{
global $db;
// The line below just assigns a string to $emailCheck. You still need to execute the query.
$emailCheck = 'SELECT email FROM user WHERE email == $email';
// Try to execute it.
$queryResult = $db->query($emailCheck);
// Check if the query succeeded and if a row is found.
// For select queries an object is returned from which you can fetch the results.
if ($queryResult !== false && $queryResult->fetch_object() === false)
{
$hashPass = password_hash($password);
// Inserting should be done in a similar way. Build a query, and execute it.
$email = $db->real_escape_string($email);
$hashPassword = $db->real_escape_string($hashPassword);
// Mind the escaping of illegal characters (above) and the quotes (below).
$statement = "INSERT INTO user VALUES ('$email', '$hashPassword')";
// Note: you won't get a result object for insert statements.
$result = $db->query($statement);
// Check the value of result to see if it worked.
}
}
答案 1 :(得分:0)
您无法执行类似的SQL查询。
试试这个:
$sql = 'INSERT INTO user VALUES ($email, $hashPassword);';
$db_con = new mysqli($host, $user, $password, $database);
$result = $db_con->query($sql);
您必须“获取”结果才能获得所需数据,请阅读文档如何使用它。 :)
答案 2 :(得分:-1)
试试这个:
function juice_sign_up( $email, $password, $password_confirm )
{
global $db;
$emailCheck = mysqli_query($db, 'SELECT email FROM user WHERE email = $email');
if($emailCheck == 'NULL'){
$hashPass = password_hash($password);
mysqli_query($db, INSERT INTO user VALUES ($email, $hashPassword));
}