I want to change the 401 in the code below to a string based on a value from my website like
$sql2 = 'SELECT post_content2 FROM wp_posts WHERE ID = '$jeff''
but I’m getting
Parse error: syntax error, unexpected ‘$jeff’ (T_VARIABLE) in /public_html/wp-content/themes/real-spaces/single-property.php on line 384
Here’s the code that works:
if(! $conn2 )
{
die('Could not connect: ' . mysql_error());
}
$sql2 = 'SELECT post_content2 FROM wp_posts WHERE ID = 401' ;
mysql_select_db('fncletvn_wp389');
$retval2 = mysql_query( $sql2, $conn2 );
if(! $retval2 )
{
die('Could not get data: ' . mysql_error());
}
while($row2 = mysql_fetch_array($retval2, MYSQL_ASSOC))
{
echo "{$row2['post_content2']} <br> " ;
}
I’m very new to programming so plase help 😀
By the way, what I’m trying to do is pull out the value of post_content2 from the database based on the ID of the current post which is $jeff
Simply use quotes like this:
This will create sql string as:
When
$jeff=401
But as per your question, if you want like this:
Just use:
FYI: Single quotes will not replace your PHP variable with value, instead it prints the variable as it is. Double quotes will do the replacement.
Either you can use the answer given by @myway or you can use mysql pre pared statements. I will recommend you to use pre-pared statements since they are secure and re usable.
Note that if you use
$sql2 = "SELECT post_content2 FROM wp_posts WHERE ID = $jeff";$sql2 = "SELECT post_content2 FROM wp_posts WHERE ID = $jeff";
as indicated by previous commenter, your$jeff
must be quoted.Just be sure to first apply
mysql_escape_string($jeff)
beforehand.Also, I now that you did not ask about this, but I absolutely have to warn you that the
mysql_*
functions are depreciated and you should never use them except when modifying existing code–in which case you should be actively changing your code to themysqli_*
variants.You’re also missing the concatenation operator in your code:
$sql2 = 'SELECT post_content2 FROM wp_posts WHERE ID = '$jeff''
PHP’s concatenation operator is
.
.Use it like this:
$sql2 = 'SELECT post_content2 FROM wp_posts WHERE ID = '.$jeff;
If $jeff is a string, not an int, you will need to encose it in quotes like this:
$sql2 = 'SELECT post_content2 FROM wp_posts WHERE ID = "'.$jeff.'"';
However if $jeff is supplied by the client in any way, you should use prepared statements to protect against mysql injection.
What PHP was trying to tell you with Parse error: syntax error, unexpected ‘$jeff’ (T_VARIABLE), is that it didn’t know why there was a variable next to a string in an assignment operation. Nor what you were trying to do with it. The concatenation operator indicates that you want that variable joined to the string next to it as if it were also a string. Which becomes an important distinction in loosely typed languages like PHP.