简体   繁体   中英

Can't insert link into mysql database

Here is a part of my insert code that troubles me:

$recepient="test@email.com";
$text="Please track: http://wwwapps.ups.com/WebTracking/processInputRequest?HTMLVersion=5.0&loc=en_US&Requester=UPSHome&tracknum=123456789&AgreeToTermsAndConditions=yes&ignore=&track.x=24&track.y=9";
$date="2013-05-03 08:12:20"; 
$through="mail";
$status=1;
$q = "INSERT INTO `messages` (`recepient`,`text`,`date`,`through`,`status`) VALUES('".mysql_real_escape_string($to)."','".mysql_real_escape_string($text)."','".date("Y-m-d H:i:s")."','".mysql_real_escape_string($rowuser['through'])."','".intval($status)."')";
try {$db->query($q);} catch(PDOException $ex) {echp" Error: ".$ex.);}

If I remove the link from the $text variable I can see the data added to the database. But in the way I need it to add with the link - the script stops not reporting any errors.

use PDO 's powerful prepared statements :

$q  = "INSERT INTO messages (recepient,text,date,through,status) ";
$q .= "VALUES (:to,:text,:date,:through,:status)";

$dbinsert = $db->prepare($q);
$dbinsert->execute(array(
    ':to' => $recipient,
    ':text' => $text,
    ':date' => $date,
    ':through' => $through,
    ':status' => $status));

This should do it.
Let PDO take care of escaping.

It would appear that you're mixing database libraries, or have wrapped things yourself.

If you're using something like mysqli or PDO for the ->query() call, then mysql_real_escape_string() will NOT work. m_r_e_s() requires an active connection to the DB to operate. Connections established in mysql, mysqli, and PDO are NOT shareable between the libraries.

That means your m_r_e_s() calls will returning a boolean FALSE for failure, and your query will actually look like:

$q = "INSERT .... VAALUES ('', '', '', etc...)";

What's the size of the text column in the database? It's mostly not the reason but I've noticed that your $text is 190 char long.

The problem is with the "?" sign in the $text variable. It is being treated as a placeholder when it is put into the query, and the $db->query expects an array of variables. The solution is to use a placeholder instead of a $text variable and submit $text variable as params:

$ar[0]=$text;
$q = "INSERT INTO `messages` (`recepient`,`text`,`date`,`through`,`status`)";
$q.= " VALUES('".$to."',?,'".date("Y-m-d H:i:s")."','".$through."',".$status.")";
$db->query($q,$ar);

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