Mysqli删除请求块

时间:2016-03-26 15:37:53

标签: php mysqli

我有一个奇怪的行为,不能让我删除我桌子上的一行,事实上,一旦它进入要求删除的mysqli->查询行,它就会停止并且什么都不做(回声帖子)在它完全没有显示之后),这是代码,我想知道什么是错的:

我在deleteLine函数中发布了使用echo正确输出的东西,以及没有使用的东西:

<?php
//here are the db connexion
include 'connDB.php';
//array that'll stock my values to delete
$myarray = array();

//lists all elements of the Table animals
if ($result = $mysqli->query("SELECT * FROM animals")) {

while($row = $result->fetch_array(MYSQL_ASSOC)) {

//searching for some specific lines
         $delay= timePassed($row["time"]);
         if($delay >= 60){
         	 //save the id of the line  in an array
         	 $myArray[] = $row["id"];
         }
    }
  
}
$result->close();

//Once all my lines to delete are saved in my array, let's delete it
for($i=0;$i<count($myArray);$i++){
//will call and delete one line by one
	deleteLine($myArray[$i]);
}
$mysqli->close();

					
////////////////////////////////////////////////////////////////////////////////////////////////TIMEPASSED
//just to compare 2 timestamps between them
function timePassed($dateToCompare){
	$dateNow = time();
	$res =round(($dateNow-$dateToCompare)/(60*60));
	return $res; 
}
////////////////////////////////////////////////////////////////////////////////////////////////DELETELINE
function deleteLine($id){
	echo $id;  //OUTPUTS CORRECTLY THE ID OF THE LINE TARGETED  (in my case : 83)
$mysqli->query("DELETE FROM animals WHERE id=".$id);
echo"line deleted"; //THIS NEVER OUTPUTS

}
?>

1 个答案:

答案 0 :(得分:2)

我不知道如何获取数据库连接对象$mysqli。在函数内部,我将global $mysqli用于使用函数外部的连接对象。

function deleteLine($id){
             global $mysqli;//database connection object
             $mysqli->query("DELETE FROM `animals` WHERE `id` ='$id'");   
             if($mysqli->affected_rows>0){
                 echo "line deleted"; 
            }else{
                 echo 'delete failed';
            }
           $mysqli->close();
     }

希望这可能有所帮助并使用documentation来提高安全性。