MySQL选择查询不起作用。

时间:2013-07-05 18:23:11

标签: php mysql

<?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点的值来找到它。

1 个答案:

答案 0 :(得分: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'];