简体   繁体   中英

PHP mysqli can't fetch data

Hy,

I have a strange problem. This is the code:

First, I get the parameters and connect to the base.

<?php
    include('connect.php');
    $id=$_GET['id']; // if I echo this, it outputs 0
    $category=$_GET['category'];// if I echo this, it outputs 'category1'
    $name=$_GET['name'];
 ?>

And now I went to fetch the data from the db:

<?php
    if ($stmt = $mysqli->prepare("SELECT modelID,modelName,modelLogo FROM model,maker WHERE model.makerID=maker.makerID AND model.makerID='.$id.' AND model.modelCategory='.$category.' ORDER BY modelName")) { 

    $stmt->execute();

    $stmt->bind_result($modelID, $modelName,$modelLogo);

    while ($stmt->fetch()) {
        echo '<a href="edit_model.php?id='.$modelID.'"><div class="box"><img src="'.$modelLogo.'" /><p>'.$modelName.'</p></div></a>';
    }

    $stmt->close();

    }

    else {
        printf("Prepared Statement Error: %s\n", $mysqli->error);
     }
?>

And this won't output nothing. But when i run the sql query in myPhpAdmin, it returns the values.

Query:

SELECT modelID,modelName,modelLogo 
FROM model,maker 
WHERE model.makerID=maker.makerID 
AND model.makerID='0' 
AND model.modelCategory='category1' 
ORDER BY modelName

Output: 0 // name // path

I put error_reporting(E_ALL); but it doesn't return any error. Also, I tried to put this code after the $stmt->bind_result($modelID, $modelName,$modelLogo); and this is the result:

var_dumb($modelID);die(); it returned '0'.

var_dumb($modelName);die(); it returned 'NULL'.

var_dumb($modelLogo);die(); it returned 'NULL'

I can't figure out what's going on so any help is needed.

It's because your query in the PHP is bogus, change this:

... AND model.modelCategory='.$category.' ...

To this:

... AND model.modelCategory='$category' ...

Or better yet, since you are already using prepared statements, use parameter binding so you don't have to worry about this kind of thing.

You are not binding the parameters. Try this.

if ($stmt = $mysqli->prepare("SELECT modelID,modelName,modelLogo FROM model,maker 
    WHERE model.makerID=maker.makerID 
    AND model.makerID = ? AND model.modelCategory = ? 
    ORDER BY modelName")) {
$stmt->bind_param('ss', $id, $category);
//rest of the code intact

Sean Bright answered your question, but I'd prefer this one:

"SELECT 
  modelID, modelName, modelLogo 
FROM 
  model, maker 
WHERE 
  model.makerID=maker.makerID AND model.makerID='{$id}' 
AND 
  model.modelCategory='{$category}' 
ORDER BY modelName"

Just because such code editors as Notepad++ hightlight variables in strings making it easy to read.

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