简单地将PHP变量插入MySQL

时间:2015-06-03 06:09:28

标签: php mysql variables insert

我有一些简单的代码,我无法正常工作。

<?php
$mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
if ($mysqli_connection->connect_error) {
   echo "Not connected, error: " . $mysqli_connection->connect_error;

   $username = 'Eddie';
   $username = mysql_real_escape_string($username);
   $email = 'eddie_the_eagle@hotmail.com';
   $email = mysql_real_escape_string($email);

   $sql = "INSERT INTO  `users` (`username`, `email`) 
           VALUES ( '".$username."', '".$email."')";
   $res = $mysqli_connection->query($sql);
}

?>

当我运行代码时,不会出现错误,但用户表仍为空。

4 个答案:

答案 0 :(得分:1)

  

你混合了两个API的 mysql mysqli 。停止使用已弃用的 mysql

DrawerLayout.SimpleDrawerListener()

您忘了关闭$username = mysqli_real_escape_string($mysqli_connection,$username); $email = mysqli_real_escape_string($mysqli_connection,$email); 条件

if

答案 1 :(得分:1)

试试这个

<?php

    $mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
    if ($mysqli_connection->connect_error)
    {
        echo "Not connected, error: " . $mysqli_connection->connect_error;
    }//Change
    $username = 'Eddie';
    $username = mysqli_real_escape_string($mysqli_connection,$username);//Change
    $email = 'eddie_the_eagle@hotmail.com';
    $email = mysqli_real_escape_string($mysqli_connection,$email); //Change

    $sql = "INSERT INTO  users (username, email) VALUES ( '".$username."', '".$email."')";

    $res = $mysqli_connection->query($sql);
?>

答案 2 :(得分:0)

您忘记关闭if语句,因此只有在出现连接错误时才会运行插入逻辑 将最后一个}移到

之后的新行
$mysqli_connection->connect_error;

答案 3 :(得分:0)

有两个问题: -

  1. 您正在将mysql_*mysqli_*

  2. 混合
  3. 没有进行错误检查。

  4. 试试这样: -

    <?php
    
        $mysqli_connection = new MySQLi('localhost', 'root', 'secret', 'edgeserver');
        if ($mysqli_connection->connect_error)
        {
            echo "Not connected, error: " . $mysqli_connection->connect_error;
        }//Change
        $username = 'Eddie';
        $username = mysqli_real_escape_string($mysqli_connection,$username);//connection link must be provided as a first parameter
        $email = 'eddie_the_eagle@hotmail.com';
        $email = mysqli_real_escape_string($mysqli_connection,$email); //same here
    
        $sql = "INSERT INTO  users (username, email) VALUES ( '".$username."', '".$email."')";
    
        $res = $mysqli_connection->query($sql);
    ?>
    

    注意: - 当您打算做任何事情时,请自己使用错误报告。感谢。