【问题标题】:mysqli_query() expects at least 2 parameters & mysqli_query(): Empty query error messages [duplicate]mysqli_query() 至少需要 2 个参数和 mysqli_query():空查询错误消息 [重复]
【发布时间】:2015-12-08 21:22:13
【问题描述】:

在运行此代码时,我遇到了 4 个错误,该代码将用户的电子邮件地址添加到名为 ecommerce 的数据库中,位于名为 subscriptions 的表中。

$con = new mysqli('localhost', 'root', '','ecommerce');

if (!$con) {
    die('Could not connect: ' . mysql_error());
}    

$errors = array();
if($_POST)
    {
        if(empty($_POST['email']))
        {
            $errors['email1'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:30px;float:right;'>Dont forget to write your email!</p>";
        }else {
            $email = test_input($_POST["email"]);

            // check if e-mail address is well-formed
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $errors['email2'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:25px;float:right;'>Something wrong is with your email</p>"; 
            }else{

                // check if the email already exists
                $query = mysqli_query("SELECT * FROM subscriptions WHERE email='$email'");
                if(mysqli_num_rows($query) > 0){
                    $errors['email3'] = "<p style='color:red;font-family: BCompset, Arial, Helvetica, sans-serif;font-size:25px;float:right;'>Your had been registered before!</p>";
                }
            }
        }

        //check errors
        if(count($errors) == 0)
        {
            $insert_email = mysqli_query("INSERT INTO subscriptions (email) VALUES ('$email')");
            $insert_email = mysqli_query($con, $insert_email);
            $success = "<script>alert('Your email was successfully added to our database!')</script>";
        }
    }

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>
<form action="" method="POST" class="searchform" dir="ltr">
                                <input type="text" name="email" placeholder="Your email address" value="<?php if(isset($_POST['email'])) echo $_POST['email']; ?>"/>
                                <button name="submit" type="submit" class="btn btn-default"><i class="fa fa-arrow-circle-o-right"></i></button>
                                <p><?php if(isset($errors['email1'])) echo $errors['email1']; ?></p>
                                <p><?php if(isset($errors['email2'])) echo $errors['email2']; ?></p>
                                <p><?php if(isset($errors['email3'])) echo $errors['email3']; ?></p>
                                <p><?php if(isset($success)) echo $success; ?></p>
                                <?php if(count($errors) == 0){echo "<p id='para' dir='rtl'>You can add your email to our emailsshow list.</p>";}?>
</form>

错误是这样的:

警告:mysqli_query() 至少需要 2 个参数,1 个在第 27 行给出

第 27 行:

$query = mysqli_query("SELECT * FROM subscriptions WHERE email='$email'");

警告:mysqli_num_rows() 期望参数 1 为 mysqli_result,第 28 行给出 null

第 28 行:

if(mysqli_num_rows($query) > 0){

警告:mysqli_query() 至少需要 2 个参数,1 个在第 37 行给出

第 37 行:

$insert_email = mysqli_query("INSERT INTO subscriptions (email) VALUES ('$email')");

警告:mysqli_query():第 38 行的空查询

第 38 行:

$insert_email = mysqli_query($con, $insert_email);

我是这个论坛的新手,如果你能帮我解决这个问题,我会最好……提前谢谢!

【问题讨论】:

    标签: php mysql forms email mysqli


    【解决方案1】:

    除了缺少 mysqli 连接资源/对象之外,脚本还有一些其他问题:

    • 我是prone to sql injections
    • 你没有测试http://docs.php.net/mysqli.quickstart.connections所示的mysql连接
    • 该脚本通常缺乏错误处理。任何 mysqli_* 函数/方法都可能失败。例如。关于mysqli_num_rows 的警告与不检查mysqli_query 的返回值有关。
    • 您的函数 test_input() 不会测试任何内容,只会更改值;并且电子邮件地址与 htmlspecialchars() 等无关。只需放弃该功能。
    • 电子邮件地址验证似乎过于复杂,没有明显优点。
    • 不要使用 SELECT/INSERT 组合来阻止电子邮件地址被插入两次,只需在该字段上创建一个 unique index,mysql 服务器就会可靠地防止重复。

    例如

    <?php
    define('MYSQL_ER_DUP_KEY', 1022); // see https://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html#error_er_dup_key
    $errors = array();
    if($_POST) // might be superfluous
    {
        // simplified email validation
        // improve if needed
        $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
        if ( !$email ) {
            // removed html/style from error message, better do that when printing the error
            $errors['email1'] = "A valid email address is required";
        }
    
        // you only need the database connection after the email address is validated
        $mysqli = new mysqli('localhost', 'root', '','ecommerce');
        // see http://docs.php.net/mysqli.quickstart.connections
        if ($mysqli->connect_errno) {
            trigger_error("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error, E_USER_ERROR);
        }
    
        // not checking if this email address is already in the database
        // instead create a unique index for that field
        // see https://dev.mysql.com/doc/refman/5.6/en/constraint-primary-key.html
        // - otherwise you'd at least have to lock the table to avoid race conditions -
    
        // sql injections: see http://docs.php.net/security.database.sql-injection
        // to prevent sql injections you either have to make sure string literals are
        // properly encoded/escaped or use preparead statements+parameters
        $stmt = $mysqli->prepare('INSERT INTO subscriptions (email) VALUES (?)');
        if ( !$stmt ) {
            trigger_error("prepare statement failed (" . $mysqli->errno . ") " . $mysqli->error, E_USER_ERROR);
        }
        else if ( !$stmt->bind_param('s', $email) ) {
            trigger_error("bind_param failed (" . $stmt->errno . ") " . $stmt->error, E_USER_ERROR);
        }
        else if ( !$stmt->execute() ) {
            // email has a unique index, inserting an email address a second time
            // results in a ER_DUP_KEY error
            if ( MYSQL_ER_DUP_KEY==$stmt->errno ) {
                $errors['email2'] = "email address already in subsription list";
            }
            else { // otherwise it's "really" an error
                trigger_error("execute failed (" . $stmt->errno . ") " . $stmt->error, E_USER_ERROR);
            }
        }
        else {
          [... inserted ...]
        }
    }
    
    【解决方案2】:

    而不是

    $query = mysqli_query("SELECT * FROM subscriptions WHERE email='$email'");
    

    使用

    $query = $con->query("SELECT * FROM subscriptions WHERE email='$email'");
    

    $query = mysqli_query($con, "SELECT * FROM subscriptions WHERE email='$email'");
    

    也代替

    $insert_email = mysqli_query("INSERT INTO subscriptions (email) VALUES ('$email')");
    

    使用

    $insert_email = $con->query("INSERT INTO subscriptions (email) VALUES ('$email')");
    

    这是我能看到的仅有的 2 个错误。

    【讨论】:

      【解决方案3】:

      像这样在 mysqli_query() 中将连接指定为参数

      $query = mysqli_query($con,"SELECT * FROM subscriptions WHERE email='$email'");
      

      一旦您得到更正查询,mysqli_num_rows 上的错误也应该消失。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-25
        • 1970-01-01
        • 2014-10-10
        • 2013-10-09
        相关资源
        最近更新 更多