在php + mysql中的数据库中插入变量

时间:2017-10-01 10:46:29

标签: php mysql

我完全是PHP初学者,我试图在PHP和MySQL的数据库中插入变量。 这是我的代码:

$link = mysql_connect('localhost','','','onlynews') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');

$strSQL = "INSERT INTO news(id, title,photo,url,source, at) VALUES('$x','$title','$url','$imgurl ','$source','$at')"; 

mysql_query($strSQL) or die(mysql_error());

问题是它在做什么:没事!完全没有条目,数据库中没有任何变化。

- 我该如何解决这个问题?

- 我是否必须编写代码以防止SQL注入,即使变量来自API,而不是来自用户?

1 个答案:

答案 0 :(得分:1)

您必须使用$conn->query($sql);执行查询。

但是,为避免SQL注入,您绝对应该使用prepared statements或至少$conn->real_escape_string()来转义SQL语句中的值。

例如,这是使用预准备语句的代码:

 $servername = "localhost";
 $username = "";
 $password = "";
 $dbname = "onlynews";
 $tableName = "news";
 $conn = new mysqli($servername, $username, $password, $dbname);
 $stmt = $conn->prepare("INSERT INTO news (id, title, photo, url, source, at)
                         VALUES (?, ?, ?, ?, ?, ?)");
 $stmt->bind_param('ssssss', $thetitle, $urlToImage, $theurl, $thesource, $thetime);
 $stmt->execute();
 $stmt->close();

您还应该添加一些错误检查,因为$conn->prepare()$stmt->execute()可能会失败(并返回false)。当然,在构造$conn期间建立与数据库的连接也可能失败,可以使用$conn->connect_error进行检查。