dongqiaozhe5070 2012-04-17 14:34
浏览 78
已采纳

清除MySQL字符串数据到明文和修剪开始/结束空间的最佳方法?

I already have data I scraped from a web table and I've noticed some leading spaces and nbsp in some entries. I realize I should have cleaned the data while scraping before inserting it into MySQL but it was a while ago and I don't feel like repeating the process if I don't have to. I came up with this PHP script (late) last night and it works up until I try to update the entries.

<?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++;
}*/
?>

Couple of questions:

  1. Is there a way to do this strictly in MySQL without using PHP?
  2. What function/s should I use to strip the strings in order to convert to plaintext and remove all leading, trailing, and nbsp spaces?
  3. The PHP script seems to work until updating the data, what gives?

Thanks

  • 写回答

4条回答 默认 最新

  • dongzice4895 2012-04-17 14:37
    关注

    There's a large number of MySQL String Functions that can help with this sort of thing.

    You might need a combination of REPLACE and TRIM to clean it up:

    UPDATE table SET column=TRIM(REPLACE(column, '&nbsp;', ' '))
    

    Also try not to use mysql_query, but use PDO instead. Writing queries directly leaves you exposed to SQL injection problems.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行