-3

I have been getting this error recently and I cant seem to fix it, I have looked at other similar questions and I cant seem to find anything that can fix this. I get this error when I try to run the code:

Parse error: syntax error, unexpected '"SELECT id FROM users WHERE ip' (T_CONSTANT_ENCAPSED_STRING) in C:\xampp\htdocs\filesharing\assets\includes\user.php on line 24

Heres my code:

<?php 
include_once("connect.php");

function generateRandomString($length = 6) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}   

$random = generateRandomString();

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

$ip_check = $conn->query"SELECT id FROM users WHERE ip = '" . $ip . "'";

if(!$ip_check) {
    die('Query failed to execute');
}

if($ip_check->num_rows == 1) {
    echo "User exists";
    $user = mysql_fetch_array($ip_check);
    echo $user;
} else {
    echo "User doesnt exist";

    $sql = "INSERT INTO users (ip, code) VALUES ('" . $ip ."', '" . $random . "')";

    if (mysqli_query($conn, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }   
}

?>

1 Answers1

0

query is a method called on an object. Methods are like functions, they are called by their name which is always followed by round brackets. Arguments are placed inside those brackets.

That means you have to enclose the argument you hand over inside brackets, here the query string:

$ip_check = $conn->query("SELECT id FROM users WHERE ip = '" . $ip . "'");

Which you can simplify to that, since php resolves scalar variables inside double quoted strings:

$ip_check = $conn->query("SELECT id FROM users WHERE ip = '$ip'");

The official php documentation has a section about OOP which offers good examples about that stuff: http://php.net/manual/en/language.oop5.basic.php

arkascha
  • 41,620
  • 7
  • 58
  • 90