Home » Php » Using php variables inside MySQL insert statement

Using php variables inside MySQL insert statement

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m using the following statement, but not sure how to get the $variables inside the statement properly:

mysql_query("INSERT INTO subscribers (email, referral_id, user_id, ip_address)
             VALUES ('$user_email', '$user_refer', '$user_share', '$_SERVER['REMOTE_ADDR']')");
How to&Answers:

Just change the last one:

mysql_query("INSERT INTO subscribers (email, referral_id, user_id, ip_address)
VALUES ('$user_email', '$user_refer', '$user_share', '".$_SERVER['REMOTE_ADDR']."')");

Answer:

When using an array type in a string (the double quotes “” mean php is going to parse that string) you have to enclose the value you want to use in curly brackets, ie

mysql_query("INSERT INTO subscribers (email, referral_id, user_id, ip_address)
         VALUES ('$user_email', '$user_refer', '$user_share', '{$_SERVER['REMOTE_ADDR']}')");

Answer:

although literal question is answered in the link in the comments, the real problem you face has nothing to do with SQL but with PHP string syntax. So, here is a link for your reference: http://php.net/types.string

This page is among most important things you have to know about PHP.
You ought to study it diligently, or you’ll be unable to use PHP for even most simple tasks like this one.

Answer:

Use it like this:

mysql_query("INSERT INTO subscribers (email, referral_id, user_id, ip_address)
             VALUES ('".$user_email."'…

Answer:

You should do it a bit differently. Use either

You can also look at the topic a sql command why it shows an error?

It’s a little bit different compared to what you do now, but a lot more safer.

Answer:

Safest way to do what you want is instead of this:

mysql_query("INSERT INTO subscribers (email, referral_id, user_id, ip_address)
         VALUES ('$user_email', '$user_refer', '$user_share', '$_SERVER['REMOTE_ADDR']')");

do this:

$query = “INSERT INTO subscribers (email, referral_id, user_id, ip_address)
VALUES (‘$user_email’, ‘$user_refer’, ‘$user_share’, ‘{$_SERVER[‘REMOTE_ADDR’]}’)”

Note the curly brackets around the index inside the $_SERVER variable. If you want to enclose a index inside a superglobal, then it’s best to use curly brackets. otherwise, use concatenation as suggested by others.