使用mysqli插入数据 [英] Inserting data using mysqli

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

问题描述

此代码通过所有调试,但是由于某种原因,它仍然没有插入.它尝试检查用户名是否已存在于数据库中,如果不存在,则将其添加.由于某种原因,它仍然不会将其添加到数据表中.它确实到达了插入部分,但没有添加行.

This code gets through all of the debugs but for some reason, it is still not inserting. It tries to check if the username already exists in the database and if it doesn't, it adds it. For some reason, it still doesn't add it to the data table. It does get to the insert part but it doesn't add a row.

<?php 
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', /*$_POST["username"]*/ $username );
$username = 'hi'; 
$stmt->execute();
$stmt->store_result();

echo "debug 2";
if ($stmt->num_rows == 0){ // username not taken
  echo "debug 3";
  $stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
  $password =(/*$_POST["password"]*/ "hey");
  $username =(/* $_POST["username"]*/ "hi");  
  $stmt2->bind_param('s',$username);
  $stmt2->bind_param('s',$password);
  $stmt2->execute();
  if ($stmt2->affected_rows == 1){
    echo 'Insert was successful.';

  }else{ echo 'Insert failed.';
   var_dump($stmt2);
  }
}else{ echo 'That username exists already.';}

?>

推荐答案

您应将所有变量与bind_param()绑定一次,而不应绑定两次或N次.正确的方法是先传递类型,然后传递变量.

You should bind all variables once with bind_param() and not twice or N times. The correct way is pass first the types followed by the variables.

更改:

$stmt2->bind_param('s',$username);
$stmt2->bind_param('s',$password);

通过

$stmt2->bind_param('ss',$username, $password);

使用php5.6> =,您可以使用...运算符传递数组以简化操作.

With php5.6 >= you can pass an array with ... operator to simplify.

$data = array('user' => 'someUser', 'password' => 'secret');
$stmt2->bind_param('ss', ...$data);

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

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