MySQLi更新查询手动工作但脚本

时间:2017-07-04 20:31:59

标签: php mysql mysqli

我正在创建一个ping IP的脚本,X值保存在MySQL数据库中以用于统计目的。

如果我接受echo(更新数据,在函数中间)并直接在PHPMyAdmin中执行完美,但在PHP代码中没有相同的查询,我已经检查了所有,我没有看到错误,洛尔。

这是代码:

    /*
    ID  Primary int(11)         No  None        AUTO_INCREMENT   Change Change   Drop Drop  
More
    2   ip  text    latin1_swedish_ci       No  None             Change Change   Drop Drop  
More
    3   timeping    text    latin1_swedish_ci       No  None             Change Change   Drop Drop  
More
    4   jsondata    text    latin1_swedish_ci       No  None             Change Change   Drop Drop  
More
    5   timeop  text    latin1_swedish_ci   
    */

$db = new mysqli ("127.0.0.1", "R_status", "PASSHIDDEN", "R_status");
//$totalIP = $db->query("SELECT COUNT(*) FROM data");
//$resultado = $totalIP->fetch_array();
//print($resultado[0]);
$prepare = $db->query("SELECT * FROM data WHERE timeping='0' LIMIT 1");
$ars = $prepare->fetch_array();
//echo($prepare-num_rows);
function pingAddress($ip) {
    $pingresult = exec("/bin/ping -c 3 $ip", $outcome, $status);
    $status++;
    global $ars;
    // 0 = NO COMPROBADO
    // 1 = EN LINEA
    // 2 = CAIDO
    echo("UPDATE data SET `timeping`='$status' WHERE ID=".$ars[0]."");
    $db->query("UPDATE data SET `timeping`='$status' WHERE ID=".$ars[0]."");
    die();
}
print_r($ars);
pingAddress($ars[1]);

?>

以下是此代码的一个输出:

Array ( [0] => 2 [ID] => 2 [1] => 77.26.0.2 [ip] => 77.26.0.2 [2] => 0 [timeping] => 0 [3] => 0 [jsondata] => 0 [4] => 0 [timeop] => 0 ) 

UPDATE data SET `timeping`='1' WHERE ID=2

该更新字符串在PhpMyAdmin中有效,但在PHP脚本中没有,对我来说更陌生,因为我没有在google中找到解决方案。

1 个答案:

答案 0 :(得分:0)

正如评论中所建议的那样,即使使用添加的global $db;,您当前的查询方式也是非常不安全的,并且对SQL注入攻击也是明智的。

我建议您按照以下方式执行更新查询,以避免发生SQL注入的风险。无论你是私人还是私人,无知都不是安全的借口!

// $db is your database connection
$query = "UPDATE `data` SET `timeping`=? WHERE `ID`=?"; // the query
$stmt = mysqli_prepare($db, $query); // prepares the query for params
mysqli_stmt_bind_param($stmt, 'ii', $status, $ars[0]); // bind two ints -> 'ii' -> passing the args behind it
mysqli_stmt_execute($stmt); // run the stmt
// use following to check the number of affected rows:
// mysqli_stmt_affected_rows($stmt) // highly recommended to check for any malicious activity!
mysqli_stmt_close($stmt); // close it -> just to do it neatly

建议通过preg_match进行额外检查,以防止在意外落入坏人手中时插入任何恶意代码。做mysqli_real_escape_string,剥离标签和修剪可能也是好主意。