John Davidson

How to include a PHP variable inside a MySQL statement


I'm trying to insert values in the contents table. It works fine if I do not have a PHP variable inside VALUES. When I put the variable $type inside VALUES then this doesn't work. What am I doing wrong?

$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description)
VALUES($type, 'john', 'whatever')");

My Answer:
You need to properly concatenate the PHP variable inside the MySQL statement. Here is the corrected code:

$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");

By adding single quotes around the `$type` variable inside the `VALUES` section of the MySQL query, you are telling MySQL that it is a string value. This should now work correctly.

Rate this post

4 of 5 based on 7794 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us