我已经从网络表中删除了数据,并且我注意到某些条目中有一些前导空格。我知道我应该在将数据插入MySQL之前清理数据,但它是在不久之前,如果我不需要,我不想重复这个过程。我昨晚提出了这个PHP脚本(已经很晚了),直到我尝试更新条目为止。
<?php
require_once("login.php");
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database);
$query = "SELECT * FROM ingredients;";
$result = mysql_query($query);
$i = 1;
$e = array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
//echo $row[1];
$str = trim(mysql_real_escape_string($row[1]));
$e[] = $str;
$i++;
}
//print_r($e);
/*
$i = 1;
foreach($e as $entry) {
$query = "UPDATE ingredients
SET ing_name = $entry
WHERE ing_id = $i;";
mysql_query($query);
$i++;
}*/
?>
几个问题:
由于
答案 0 :(得分:3)
我认为这将严格使用SQL查询为您完成:
UPDATE ingredients SET column_with_spaces = TRIM(column_with_spaces)
就未来的搜索而言,在插入数据库之前使用trim()
。
答案 1 :(得分:3)
有很多MySQL String Functions可以帮助解决这类问题。
您可能需要REPLACE
和TRIM
的组合来清理它:
UPDATE table SET column=TRIM(REPLACE(column, ' ', ' '))
另请尝试不使用mysql_query
,而是使用PDO。直接编写查询会使您面临SQL注入问题。
答案 2 :(得分:0)
如果你正在寻找一个用于字符串修剪和替换的mysql解决方案,你应该看看这里找到的mysql字符串函数:
修剪:http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_trim 替换:http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace
答案 3 :(得分:0)
//The PHP keyword <b>strtr()</b> is much easier to understand: <br>
$query = "SELECT * FROM ingredients";<br>
$query= strtr($isql, array(' ~;' => ' ')) ; //without the ~<br>
//Converts all HTML spaces back to white spaces for MySQL to understand.<br>
//Useful when you load data onto textboxes:<br>
//Let's say you have a surname Van Der Merwe with white spaces.<br>
//To edit the surname we need to put it into an input textbox:<br>
$DBConnect = new mysqli("localhost", "root","Userpassword", "DBName");<br>
对于关联数组:
if ($result = mysqli_query($DBConnect, $query)) {<br>
while ($row = mysqli_fetch_assoc($result)) {<br><br>
echo "<>input type='text' name='Surname' size='45' value=";<br>
echo <b>strtr</b>($row['Surname'], array(' ' => '&nbs#p;')) ;//remove the # "<br>
echo ">";<br><br>
对于非关联数组:
if ($result = $DBConnect->query($SQLstring)) {<br>
while ($row = $result->fetch_row()) {<br>
echo "<dd><>input type='text' name='Surname' size='45' value=";<br>
echo <b>strtr</b>($row[2], array(' ' => ' #;')) ; //remove the #<br>
echo ">";<br>