jquery没有从mysql数据库加载带空格的数据

时间:2017-08-28 16:50:02

标签: php jquery

使用jquery从我的数据库中检索数据时遇到了一些问题。

这是我的client.js

function get_sede_data(client) {
  $('#client-detail-co').load('client.php?name='+client);
}

这是我的client.php文件

<?php

$name = $_GET['name'];
$sql_name = "select * from client where c_name = $name";
$re_sql_name = mysqli($con, $sql_name);

if (mysqli_num_rows($re_sql_name) > 0) {
    while ($row = mysqli_fetch_assoc($re_sql_name)) {
        echo
        "<h1>Client details: {$row['c_name']}</h1>";
    }
} else {
    echo "ERROR" . mysqli_error($con);
}
mysqli_close($conexion);
?>

这通常适用于只有一个名字的客户(例如:乔治)但是有两个名字的客户(例如:玛丽安),它不起作用。知道为什么它没有用空格检索名字吗?

1 个答案:

答案 0 :(得分:1)

要解决您的问题,您需要使用单引号将变量括起来,因为它是一个字符串而不是整数。

$name = $_GET['name'];
$sql_name = "select * from `client` where `c_name`='$name'";
$re_sql_name = mysqli($con, $sql_name);

if(mysqli_num_rows($re_sql_name) > 0) {
    while($row = mysqli_fetch_assoc($re_sql_name)) {
        echo "<h1>Client details: {$row['c_name']}</h1>";
    }
} else {
    echo "ERROR" . mysqli_error($con);
}
//you had this as "conexion" but you used "con" above, so I changed this to "con"
mysqli_close($con);

您还应该转换为使用预准备语句:

MySQLi准备好的陈述

$name = $_GET['name'];

/* prepare statement */
if ($stmt = $mysqli->prepare("select `c_name` from `client` where `c_name`= ?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $name);

    /* execute query */
   $stmt->execute();

    /* bind variables to prepared statement */
    $stmt->bind_result($c_name);

    /* if num_rows > 0 then fetch values */
    if($stmt->num_rows > 0) {
        while ($stmt->fetch()) {
            echo "<h1>Client details: {$c_name}</h1>";
        }
    } else {
        //error reporting
    }

    /* close statement */
    $stmt->close();
}
/* close connection */
$mysqli->close();

PDO准备陈述

这是我个人推荐的,因为我发现它比mysqli更容易。

首先,您需要将连接处理程序更改为:

$host = 'localhost';
$db   = '';
$user = '';
$pass = '';
$charset = 'utf8';

$dsn = "mysql:host={$host};dbname={$db};charset={$charset}";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);

注意:我们在这里编辑了一些默认的数据库连接内容,最明显的是ATTR_EMULATE_PREPARES。如果这是真的,那么可以模拟准备好的语句,这些语句可以像字符串连接一样安全

然后,您的查询将如下所示:

stmt = $pdo->prepare("SELECT * FROM `client` WHERE `c_name`= ?");
$stmt->execute([$name]);
$results = $stmt->fetchAll();

if($results > 0) {
    foreach($results as $result) {
        echo "<h1>Client details: {$result['c_name']}</h1>";
    }
} else {
    //error reporting
}