[英]Update every row in a table with PHP in mySQL database
Table
*------------------------------------------------*
| id | title | filename |
*------------------------------------------------*
Lets say this is the structure of the table. 让我们说这是表格的结构。 I want to update every single row of this table.
我想更新此表的每一行。
Lets say i want to replace every space in Filename with a underscore. 假设我想用下划线替换Filename中的每个空格。
$new_filename = str_replace(" ", "_", $filename);
mysql_query("UPDATE table SET Filename = '$new_filename'");
This does not work. 这不起作用。 Each row has different Filename.
每行都有不同的文件名。
I would simply do this: 我会这样做:
mysql_query("UPDATE table SET Filename = REPLACE(Filename, ' ', '_')");
This way you only execute one command and depending on your table size, this should be pretty quick 这样你只执行一个命令,根据你的表大小,这应该很快
*edited *编辑
First answer is way better :) 第一个答案是更好:)
So your filename is in every row the same? 那你的文件名在每一行都一样吗? otherwise this code would replace all the filenames with one name.
否则此代码将用一个名称替换所有文件名。 You will need a for loop get the data from the table and update it.
您将需要一个for循环从表中获取数据并更新它。
Like this: 像这样:
$query = "SELECT id, filename FROM table";
$result = mysql_query($query);
if($result){
$num = mysql_numrows($result);
$i=0;
while ($i < $num) {
$new_filename = str_replace("_", " ", mysql_result($result,$i,"filename"));
$id = mysql_result($result,$i,"id");
mysql_query("UPDATE table SET filename = '$new_filename' WHERE id='$id'");
}
}
That will work, provided you have connected to the database using mysql_connect() first. 如果您首先使用mysql_connect()连接到数据库,那将会有效。
If you are just doing this as a one-off your solution is fine - but if you are allowing users to do this via a form of some kind then you have a security flaw called SQL Injection. 如果您只是将其作为一次性使用,那么您的解决方案就可以了 - 但如果您允许用户通过某种形式执行此操作,那么您就会遇到一个名为SQL Injection的安全漏洞。 If the variable $filename is submitted by a user, then they could end the query and start a new one.
如果变量$ filename是由用户提交的,那么他们可以结束查询并开始一个新查询。 You should never place unsanitised data into a MySQL query.
您永远不应将未经过处理的数据放入MySQL查询中。
To get round this put $filename through mysql_real_escape_string or even better use prepared statements provided by MySQLi or PDO. 为了解决这个问题,可以通过mysql_real_escape_string放置$ filename,甚至更好地使用MySQLi或PDO提供的预处理语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.