mysqli_query() expects at least 2 parameters & mys

2019-01-20 20:13发布

I got 4 errors while running this code that add the email address of the user to the database called ecommerce in the table called 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>

The errors are like this:

Warning: mysqli_query() expects at least 2 parameters, 1 given on line 27

Line 27:

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

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given on line 28

Line 28:

if(mysqli_num_rows($query) > 0){

Warning: mysqli_query() expects at least 2 parameters, 1 given on line 37

Line 37:

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

Warning: mysqli_query(): Empty query on line 38

Line 38:

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

I'm new at this forum and it would best if you can help me with that cause I really do know to do ... thanks in advance!

3条回答
干净又极端
2楼-- · 2019-01-20 20:39

Specify your connection as a parameter in your mysqli_query() like this

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

Once you get the query corrected the error on mysqli_num_rows should go away also.

查看更多
3楼-- · 2019-01-20 20:42

Instead of

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

use

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

or

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

Also instead of

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

use

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

These are the only 2 errors that I could see.

查看更多
神经病院院长
4楼-- · 2019-01-20 20:52

In addition to the missing mysqli connection resource/object there are some other issues with the script:

  • it's prone to sql injections
  • you're not testing the mysql connection as shown at http://docs.php.net/mysqli.quickstart.connections
  • the script in general lacks error handling. Any of the mysqli_* functions/methods may fail. E.g. the warning regarding mysqli_num_rows is related to not checking the return value of mysqli_query.
  • your function test_input() doesn't test anything but changes the value; and an email address has nothing to do with htmlspecialchars() et al. Just drop that function.
  • the email address validation seems overly complex without obvious merit.
  • Instead of a SELECT/INSERT combo to hinder an email address from being inserted twice just create a unique index on that field and the mysql server will reliably prevent duplicates.

e.g.

<?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 ...]
    }
}
查看更多
登录 后发表回答