Getting a PHP Parse error: syntax error, unexpecte

2019-09-20 08:13发布

问题:

On line 17 I'm receiving this error and am not sure what to correct regarding it. It seems to be something about mysqli call to the query function.

if (isset($_POST['un'])) {
    $user = sanitizeString($_POST['un']);
    $pass = sanitizeString($_POST['pw']);

if($user == "" || $pass == "")
    $error = "Not all fields were entered";
    }
else{
    $sql = "SELECT username, password FROM `Info` WHERE username = '$user'AND pass = '$pass'";
    $result = mysqli->query($sql);
if($result->num_rows == 0){
    $error = "Invalid login attempt";
    }
else {
    $_SESSION['un'] = $user;
    $_SESSION['pw'] = $pass;
    die("You are now logged in.");
    }
    }```

HP Parse error:  syntax error, unexpected '->' (T_OBJECT_OPERATOR) in /Applications/MAMP/htdocs/onsubmitlogin.php on line 17

I tried to read and debug the code myself but I don't recognize a syntactical error

回答1:

I don't know where you created a connection object of your database. Before doing a query you have to create a connection object and then query. Example:

$mysqli = new mysqli("your_host", "your_user", "your_password", "your_db_name");
$sql = "SELECT username, password FROM `Info` WHERE username = '$user'AND pass = '$pass'";
$result = $mysqli->query($sql);

Your code have a syntax error. Code line is:

$result = mysqli->query($sql);
//       ^^^^^^^          

Here mysqli should be an connection object.

For clear understanding reference.

Also suggest you to bind your parameter to make a risk (SQL injection) free query. Example:

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ss", $user,$pass);
$stmt->execute();


标签: php mysqli