You're doing it wrong.
The whole point (well, one of the main ones) of using Prepared Statements is that you set the statement and then separately insert the variables so that the variables are never a risk to the SQL statement.
Your SQL query:
$getProjectId = $mysqli->prepare('SELECT project_id FROM projects
WHERE project_name = '.$projectName);
What you currently have here is a prepared statement which is shaped as if it is a standard non-prepared old fashioned MySQLi statement. This means that the variable $projectName
can contain any data and can directly abuse your SQL query.
What you need to do instead is to substitute the variable for placeholders and then add the variables later, this is called preparing the SQL, there is a LOT of guidance on Stackoverflow and the internet at large about doing this, so please, please research it, but the outcome will look like this:
$getProjectId = $mysqli->prepare("SELECT project_id FROM projects
WHERE project_name = ?");
$getProjectId->bind_param("s",$projectName);
$getProjectId->execute();
//carry on as before
This bind_param
code inserts the variable into the ?
placeholder location, completely avoiding SQL injection issues.
Answering your Question
MySQL uses backticks
` <== This, typically next to the number 1 on your keyboard
and uses single quotes '
, so when you have a column name and/or reference value names in an SQL string they will be encased in a single quote. This will cause you issues if you wrap the whole string in single quotes in PHP. This is the error you're facing here.
Your Original query:
'SELECT project_id FROM projects WHERE project_name = '.$projectName
Should be (ignoring the detail above, that is really should be prepared properly):
"SELECT project_id FROM projects WHERE project_name = '$projectName' "
I hope you can notice the string is now encased in double quotes and the column value is encased in single quotes.
Aslo, as stated by djxyz and Aynbar in comments, you really should look into getting error feedback so that MySQL can then tell you why a query doesn't work, error messages are very useful in both MySQL and PHP .
In Conclusion
Properly using prepared statements negates the main syntax error that you originally had with column names in quotes (unneeded if it's a placeholder ?
). Always make a habit of writing SQL strings in double quotes "
to sidestep these sort of issues.
Finally, do be careful as PDO
and MySQLi
have slightly different Prepared syntax (so when you're reading SO posts, try and establish if the code is MySQLi
or PDO
before copying it!
Using Prepared Statements properly will do wonders for your abilities as a coder. It will also keep your code much safer. And it can occasionally help you mingle at parties.