dongshi2588 2013-08-12 00:34
浏览 188
已采纳

“没有选择数据库”

So I am having trouble inserting data into my database. The current error I have is a "No database selected" error but I can't see where the issue is. My code is:

<?php

$con=mysqli_connect("localhost","root","","db_test");

// Check connection

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$firstname=$_POST['firstnameReg']; 
$surname=$_POST['surnameReg'];
$mypassword=$_POST['passwordReg']; 
$email=$_POST['emailReg'];


$result= mysql_query("INSERT INTO tbl_customers (firstname, lastname, email, password) VALUES ('$firstname', '$surname', '$email', '$mypassword'");

echo "$firstname", "$surname", "$mypassword", "$email";

if($result)
{
    echo "Success!";
}
else
{
    die(mysql_error());
}

mysqli_close($con);
?>

Can you see any errors? I know it's not protected against SQL injection, it's just a test project. Thank you.

  • 写回答

3条回答 默认 最新

  • dongshu4755 2013-08-12 00:45
    关注

    Instead of mysql_query which is from the wrong library, you should use mysqli_query

    $result= mysql_query("INSERT INTO tbl_customers (firstname, lastname, email, password) VALUES ('$firstname', '$surname', '$email', '$mypassword'");
    

    So in your case, you're also missing the closing parenthesis from the VALUES:

    $result = mysqli_query($con, "INSERT INTO tbl_customers (firstname, lastname, email, password) VALUES ('$firstname', '$surname', '$email', '$mypassword')");
    

    Taking the opportunity you should also implement prepared statement to avoid SQL injection:

    $sql = "INSERT INTO tbl_customers (firstname, lastname, email, password) VALUES (?, ?, ?, ?)";
    if (!$insert = $con->prepare($sql))
        die('Query failed: (' . $con->errno . ') ' . $con->error);
    
    if (!$insert->bind_param('ssss', $firstname, $surname, $email, $mypassword))
        die('Binding parameters failed: (' . $insert->errno . ') ' . $insert->error);
    
    if (!$insert->execute())
        die('Execute failed: (' . $insert->errno . ') ' . $insert->error);
    else
        echo "Success!";
    
    mysqli_close($con);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真