我的代码中哪种语法正确?

时间:2017-04-19 13:56:51

标签: php mysql

我正在使用ajax从mysql数据库中搜索。

但是我在查询语法中遇到错误,说错误靠近division = UNKNOWN。

什么是正确的语法

代码:

<?php
 include('db.php');

 if(isset($_POST['division'])){
  $division=$database->filter($_POST['division']);
   $check_user = array(
     'division' => $division 
     );
   $exists = $database->exists( 'tablename', 'division', $check_user );

   if ($exists){    
         $sql2 = "select * from tablename where division = '".$division."' group by branch order by branch ASC";

        $sql=$database->get_results($sql2);
        echo '<option value="">--Select Branch--</option>';
         foreach($sql as $row){
             $name=$row['branch'];
             echo '<option value="'.$name.'">'.$name.'</option>';
             }
    }
  }
 ?>

这是对的吗?

1) 
$sql2 = "select * from tablename where division = '".$division."' group by branch order by branch ASC";

或者

2)
$sql2 = "select * from tablename where division = '$division' group by branch order by branch ASC";

1 个答案:

答案 0 :(得分:1)

  

正如许多评论(Joshua Bakker / Saty / ADyson)所述,你应该真的考虑使用PPS : Prepared Parameterized Statements。这将有助于Preventing SQL injection

这是您可以使用的原始示例(请根据您的需要进行调整):

<?php

error_reporting(E_ALL); ini_set('display_errors', 1); /* let PHP help us */

$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */

/* store in PHP variable */
/* you may also want to perfom some other/more checking on this var */
/* NEVER trust user side data */
$division = $_POST['division'];

echo"[ division -> $division ]"; /* just checking value -> to be removed */

/* connexion to db */
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");

if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); }

/* make sure 'tablename' and 'branch' use below are correct -> adapt to your needs */
$query = " SELECT `branch` FROM `tablename` WHERE division=? GROUP BY `branch` ORDER BY `branch` ASC ";

$stmt = $mysqli->prepare($query); /* prepare query */

$stmt->bind_param("s", $division); /* bind param will sanitize : 
here we make use of $var 'division' with 's' because it's a string AFAIK */

print_r($stmt->error_list); /* any error ? */
print_r($stmt->get_warnings()); /* any error ? */
print_r($stmt->error); /* any error ? */

$results = $stmt->execute();
$stmt->bind_result($branch); /* we use the result of the query */
$stmt->store_result();

if ($stmt->num_rows > 0) {

echo '<option value="">--Select Branch--</option>';

while($stmt->fetch()){

echo '<option value="'.$branch.'">'.$branch.'</option>';
}
}
else
{ echo"[ no data ]"; }
?>