在sql中获取2个变量并在PHP中减去它们

时间:2018-01-23 17:58:17

标签: php sql

我有多行数据,有些包含mysql表kjoring中的数据,有些则不包含数据。 我能够正确echo $km1$km2,但我无法减去它们以找到结果并回显$ km0

$sqlq = "SELECT kjoring FROM oko WHERE kjoring!='' ORDER BY logdate DESC LIMIT 2";

    if ( array_key_exists( 'field' , $out ) ) {
    $sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
  }
  $conn = new mysqli($servername, $username, $password, $dbname);

  $result = mysqli_query( $conn , $sqlq );

  if ( $result->num_rows  > 0 ) {
  while($row = mysqli_fetch_array($result)) {

  $km1 = $row[0]; 
  $km2 = $row[1];

$km0 = $km1 - $km2 ;  
  }
}

echo $km0 ;

1 个答案:

答案 0 :(得分:1)

首先要做的事情:https://github.com/aspnet/SignalR/tree/dev/samples/ChatSample Little Bobby 。了解your script is at risk for SQL Injection Attacksprepared语句。即使MySQLi也不安全!

下一步:

// $sqlq = 'SELECT ... FROM ... ORDER BY ... LIMIT'
if ( array_key_exists( 'field' , $out ) ) {
    $sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}

WHERE之后添加LIMIT条件时,数据库会返回语法错误。您需要在WHERE之后和FROM之前添加ORDER BY条件。

$sqlq = 'SELECT ... FROM ... ';    
if ( array_key_exists( 'field' , $out ) ) {
    $sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
$sqlq .= 'ORDER BY ... LIMIT ...';

现在到2个结果:

while($row = mysqli_fetch_array($result)) {
    $km1 = $row[0]; 
    $km2 = $row[1];

使用var_dump()打印行时,您会发现只有一列。你只选了一个。

使用mysqli_fetch_all($result,MYSQLI_ASSOC);,您将获得包含两行的数组。使用它,您可以进行计算。

escaping the string