cannot store php string variables into mysql table

731
error_reporting(E_ALL);
$address = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";    
$ip = getenv('REMOTE_ADDR');
$plugin='http://www.geoplugin.net/php.gp?ip='.$ip;
$geo = unserialize(file_get_contents($plugin)); 
$country = $geo['geoplugin_countryName'];
$city = $geo['geoplugin_city'];

var_dump($country) // string(6)"Serbia"
var_dump($city) // string(8)"Belgrade"

try
{
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO visits (country,city,address) VALUES (:country,:city,:address)";
$q = $conn->prepare($sql);
$q->execute(array(':country'=>$country,
                  ':city'=>$city,
                  ':address'=>$address
                  ));
} catch ( PDOException $exception )
{
    echo "PDO error :" . $exception->getMessage();
}

address is stored into the table, butcountry andcity ARE NOT. Both columns are ofvarchar type.

NULL value is displayed instead.

There is no error reported.

Just for test, I changed':country'=>$country, to':country'=>"USA", and it works.

506

Answer

Solution:

You need to bind the parameters -

$sql = "INSERT INTO visits (country,city,address) VALUES (:country,:city,:address)";
$sql->bindParam(':country', $country, PDO::PARAM_STR);
$sql->bindParam(':city', $city, PDO::PARAM_STR);
$sql->bindParam(':address', $address, PDO::PARAM_STR);
$sql->execute();

People are also looking for solutions to the problem: php - Centos-Webpanel Server Module, Login to Control Panel 404 error in WHMCS

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.