简体   繁体   中英

MySQL select query not working.

<?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;
}
?>

why my Sql queries are not working? There is no problem in database. but the queries does not execute. i want to find the distance in this program which is found out by subtracting values at points A and B.

If station is a varchar, then you need quotes around the string.

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

However, you should not ever interpolate values in a string like that. Please use prepared statements!

Read this reference, it will make your code and life a lot easier: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

edit You can also do the math in 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'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM