skip to Main Content

This query works fine:
$query = "SELECT * from hired WHERE username = 'kaas' and dvd = 'dvd 2'";

But then I change it to this query:
$query = "SELECT * from hired WHERE username = " . $_SESSION['name'] . " AND dvd = " . $_POST['dvd'];

and it doesn’t work, even though the values should be the same as the top query. It goes straight to my error message, You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘2’ at line 1

The dvd’s are having names like ‘dvd 1’ ‘dvd 2’ ‘dvd 3’. Why is it not working? Is there anything wrong in my query?

I tried to use the query with the data written down instead of using the session and post. It worked as I expected, and showed me an echo.

3

Answers


  1. Chosen as BEST ANSWER

    It needs to be

    $query = "SELECT * from hired WHERE username = '" . $_SESSION['name'] . "'" . "AND dvd = '" . $_POST['dvd'] . "'";
    

    I forgot to put a ' around them, so it would see it (for example) as 'username = Fal' instead of 'username = 'Fal'


  2. You have to concatenate variables inside query properly. Try this it will work.

    $query = "SELECT * from hired WHERE username = '" . $_SESSION['name'] . "' AND dvd = '".$_POST['dvd']."'";
    
    Login or Signup to reply.
    1. You are not wrapping your string values in quotes
    2. You must use prepared statements for security reasons (SQL Injection and escaping invalid values
    $query = "SELECT * from hired WHERE username = :name AND dvd = :dvd";
    
    $statement = $pdo->prepare($query);
    
    $statement->execute([':name' => $_SESSION['name'], ':dvd' => $_POST['dvd']]);
    $result = $statement->fetchAll();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search