简体   繁体   English

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

[英]Inserting variables in database in php + mysql

I'm totally PHP beginner, and I'm trying to insert variables in a database in PHP and MySQL.我完全是 PHP 初学者,我正在尝试在 PHP 和 MySQL 的数据库中插入变量。 This is my code:这是我的代码:

$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());

The problem is it is doing: NOTHING!问题是它正在做:什么都没有! No Entries at all, Nothing changes in the database.根本没有条目,数据库中没有任何变化。

-How can I fix this? -我怎样才能解决这个问题?

-Do I have to write codes to prevent SQL Injection, even if the variables are coming from an API, not from users? - 我是否必须编写代码来防止 SQL 注入,即使变量来自 API,而不是来自用户?

You have to execute your query using $conn->query($sql);您必须使用$conn->query($sql);执行查询$conn->query($sql); . .

However, to avoid SQL injections you should definitely use prepared statements or at least $conn->real_escape_string() to escape the values in your SQL statement.但是,为了避免 SQL 注入,您绝对应该使用准备好的语句或至少$conn->real_escape_string()来转义 SQL 语句中的值。

For example, this is your code using prepared statements:例如,这是您使用准备好的语句的代码:

 $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();

You should also add some error checking, since $conn->prepare() and $stmt->execute() may fail (and return false ).您还应该添加一些错误检查,因为$conn->prepare()$stmt->execute()可能会失败(并返回false )。 Of course, establishing the connection to the database during the construction of $conn could also fail, which can be checked using $conn->connect_error .当然,在$conn构建过程中建立到数据库的$conn也可能失败,可以使用$conn->connect_error进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM