-1
<?php
$hostname='localhost';
$user='root';
$password='';
$connect=mysqli_connect($hostname,$user,$password,'a_railway');

if(!$connect)
 {
   die('Could not connect');
  }

$rs="central";
$rd="central";
$s="A";
$d="B";

$dist=call_dist($rs,$rd,$s,$d,$connect);
echo $dist;

function call_dist($rs,$rd,$s,$d,$connect)
{
    $src_dist="SELECT Distance FROM $rs WHERE Station=$s ";
    $dest_dist="SELECT Distance FROM $rs WHERE Station=$d "; 
    $src_dist=mysqli_query($connect,$src_dist);
    $dest_dist=mysqli_query($connect,$dest_dist);
     $dist=abs($src_dist-$dest_dist);
    return $dist;
}
?>

为什么我的 Sql 查询不起作用?数据库没有问题。但查询不执行。我想在这个程序中找到距离,这是通过在点 A 和 B 处减去值来找到的。

4

1 回答 1

3

如果station是 varchar,那么您需要在字符串周围加上引号。

$src_dist="SELECT Distance FROM $rs WHERE Station='$s' ";

但是,您永远应该在这样的字符串中插入值。请使用准备好的语句!

阅读此参考资料,它将使您的代码和生活更轻松: http: //php.net/manual/en/mysqli.quickstart.prepared-statements.php

编辑您还可以在 sql 中进行数学运算:

$dist_query = mysqli_query("SELECT ABS(s.Distance - d.Distance) as dist FROM
                ( SELECT Distance FROM $rs WHERE Station='$s' ) as s,
                ( SELECT Distance FROM $rs WHERE Station='$d' ) as d");
$dist_result = $dist_query->fetch_assoc();
return $dist_result[0]['dist'];
于 2013-07-05T18:24:20.750 回答