简体   繁体   中英

Using php variables inside MySQL insert statement

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']')");

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']."')");

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']}')");

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.

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.

Use it like this:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM