【问题标题】:Continue remaining loop when the operation fails in middle中间操作失败时继续剩余循环
【发布时间】:2016-03-10 07:27:17
【问题描述】:

我在xml 中有一个大型数据集,要导入mysql 数据库。我的代码工作正常,但问题是,一些无效的描述字符串/字符会中断操作并且循环在中间停止。我想要的是,如果循环在某行中断,我想继续休息。我尝试了TRY CATCH 和 mysql_real_escape_string,它们似乎无法正常工作,或者我可能以错误的方式放置它。任何想法谢谢。

$imagearray = simplexml_load_file('imagelist.xml') or die("Error: Cannot create object");

foreach($imagearray as $image){
    $name = $image->$imgname;
    $description= $image->$description;

    $image = "INSERT INTO `tbl_image` (`imagename`, `imagedescription`) VALUES ( '".$name."', '".$description."')"; 
    $conn->query($image);
}

【问题讨论】:

  • 使用 try catch 的代码是什么样的?这是正确的方法
  • 我只是在 foreach $imagearray = simplexml_load_file('imagelist.xml') or die("Error: Cannot create object"); 之后添加它foreach($imagearray as $image){ try{ $name = $image->$imgname; $描述= $图像->$描述; $image = "插入tbl_image (imagename, imagedescription) 值 ('".$name."', '".$description."')"; $conn->查询($image); }catch(Exception $e){ 继续; } }

标签: php mysql xml


【解决方案1】:

转义输入/使用的准备好的语句,您不会遇到查询被破坏的问题。

$imagearray = simplexml_load_file('imagelist.xml') or die("Error: Cannot create object");

foreach($imagearray as $image){
    $name = $image->$imgname;
    $description= $image->$description;

    $image = "INSERT INTO `tbl_image` (`imagename`, `imagedescription`) VALUES ( ?, ?)"; 
    $prep = $conn->prepare($image); //prepare the query
    $prep->bind_param("ss", $name, $description); //bind params
    $prep->execute(); //execute
}

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    相关资源
    最近更新 更多