I'm trying to pass multiple values from a PHP URL using a Get statement. I feel like it should be pretty simple. I've managed to pass one variable fine but the second variable always ends up being NULL for some reason.
Here is my code:
<?php
$DB_HostName = "localhost";
$DB_Name = "prototype3DB";
$DB_User = "root";
$DB_Pass = "root";
$DB_Table = "sqlTable";
if (isset ($_GET["date"]))
$date = $_GET["date"];
else
$date = "null";
if (isset ($_GET["fname"]))
$fname = $_GET["fname"];
else
$fname = "null";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = "insert into $DB_Table (date, fname) values ('$date','$fname')";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "failed";
}// end else
?>
The date variable always gets passed to the database but fname is the one that ends up NULL. I kind of have the feeling it's a problem with syntax but then again I'm pretty new to PHP.
Basically, I think this line is the problem:
$sql = "insert into $DB_Table (date, fname) values ('$date','$fname')";
I appreciate any help.
Thanks.
Try this...
$sql = "insert into $DB_Table (date, fname) values ('$date','".$fname."')";
Sometimes those extra quotes solve problems...lol
But Colin is right too....the vulnerability here is quite apparent. Hopefully you're just testing things.. :)
Please use PDO or MySQLi instead of the mysql_*
functions. I like PDO and useful information can be found here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers and http://us.php.net/manual/en/pdostatement.bindvalue.php
For a quick primer examine this code:
<?php
// Credentials. DSN is a string defining how to connect to the DB
$DB_DSN = "mysql:dbname=myDatabase;host=127.0.0.1";
$DB_USER = "myUser";
$DB_PASSWD = "myPassword";
// Make the connection and get a handle for talking to the db
$db = new PDO($DB_DSN, $DB_USER, $DB_PASSWD);
// Make query into a prepared statement. Protects us from SQL injection.
// Use placeholders like :status and :id where we will be inserting variables
$statement = $db->prepare('
UPDATE users
SET status = :status
WHERE id = :id ');
// Associate vars with the placeholders in our query
// Define the type of valus such as string or int with the third param
$statement->bindValue(':id', $_GET['id'], PDO::PARAM_INT);
$statement->bindValue(':status', $_GET['status'], PDO::PARAM_STR);
// Actually run the query
$statement->execute();
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.