rbazzle
rbazzle

Reputation: 33

Why do I get this SQL syntax error? - Syntax error or access violation: 1064

Why do I get this error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1?

<?php
include'model.php';

global $db;
	try {
		$sql ='SELECT accounts.username '
		. 'FROM accounts '
		. 'WHERE accounts.username = '
		.$_POST[username];
		$stmt = $db->prepare($sql);
		$stmt->execute();
		$navList = $stmt->fetchAll();
		$stmt->closeCursor();

		header('location: ./view_cms.php');


	} catch (PDOException $exc) {
		 echo $exc->getMessage();
		// header('location: ./view_error.php');
		exit;
	}

	?>

Upvotes: 0

Views: 83

Answers (1)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Because you need to wrap strings in single quotes in the WHERE clause. You also need to access $_POST entries with a quoted string key:

$sql = "SELECT accounts.username ".
       "FROM accounts ".
       "WHERE accounts.username = '".$_POST["username"]."'";

Plus, this is the reason why PHP based web software has a bad reputation. Sanitize your inputs, for heaven's sake!! Your prepare statement doesn't do anything as you're not using parameters (your statement is not a prepared statement).

Upvotes: 1

Related Questions