无法在MySQL数据库中插入数据


Unable to insert data in MySQL database

这是我的代码

mysql_connect('localhost', 'root', 'password');
mysql_select_db('db');
mysql_query("INSERT INTO metabase(url, title, image, description) VALUES('http://www.imgur.com/', '$title', '$image', '$descr')") or die();

它并没有显示任何错误,但这些值并没有插入数据库中。我的表名是元数据库。url、title、image是varchar(255)和描述文本。这是错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's visual storytelling community. Explore, share, and discuss the best visual sto' at line 1

这是的描述

The Internet's visual storytelling community. Explore, share, and discuss the best visual stories the Internet has to offer.

所以这是因为',我该如何纠正它?

我建议使用PDO或MYSQLi,因为MySQL_已折旧。不仅如此,你还没有逃避你的价值观,并将自己暴露在一些问题中,比如MySQL注入

$pdo = new PDO("mysql:host=localhost;dbname=db","root","password");
$query = $pdo->prepare("INSERT INTO `metabase` (url, title, image, description) VALUES(:url, :title, :image, :descr)");
$query->bindValue(":url", "http://www.imgur.com", PDO::PARAM_STR);
$query->bindValue(":title", $title, PDO::PARAM_STR);
$query->bindValue(":image", $image, PDO::PARAM_STR);
$query->bindValue(":descr", $descr, PDO::PARAM_STR);
$query->execute();

在将数据插入数据库之前,需要对其进行转义。描述中的一个游离撇号会给你带来问题:

$descr = mysql_real_escape_string($descr);

请停止使用mysql_*函数。它们不再被维护,并被正式弃用。

  • 请转而了解准备好的语句,并将PDO与准备好的报表一起使用