无法从数据库中获取数据

时间:2015-01-14 17:23:51

标签: php html mysqli

connect.php:

<?php
$db = new mysqli('localhost', 'root', '', 'cms');
if ($db->connect_errno) {
    die('Sorry, We are having some problems');
}

function escape($string){
    return htmlentities($string,ENT_QUOTES,'UTF-8');
}

?>

printdata.php:

<?php 
require 'include/connect.php';
$cerid = escape($_POST['cerid']);
$student = escape($_POST['student']);

if($result = $db->query("SELECT * FROM certificate WHERE name = {$student} ")){
    if ($result->num_rows) {
        $rows =$result->fetch_assoc();
        echo $rows['cerid'];
        echo "<br>  {$rows['name']} ";
        echo $rows['cname'];
        echo $rows['dname'];
     }
}
?>

1 个答案:

答案 0 :(得分:1)

你有两个问题:

  1. 您没有引用自己的价值观。当你不使用准备好的陈述(推荐......)时,你应引用它们;
  2. 您有潜在的SQL注入问题。 htmlentities()并不能保护你。
  3. 应该是这样的:

    function escape($string, $mysqli){
        return mysqli_real_escape_string($mysqli, $string);
        // or
        return $mysqli->real_escape_string($string);
    }
    

    调用你的函数:

    $cerid = escape($db, $_POST['cerid']);
    // etc.
    

    if($result = $db->query("SELECT * FROM certificate WHERE name = '{$student}' ")){
    

    虽然准备好的陈述可以省去逃避价值的麻烦。