Skip to content
Advertisement

MYSQL prepared statment query not matching WRITTERID with WRITTER

I am trying to query a mysql statement to give match the writterid and writter in a drop down. How should i set this up because everything looks correct?

I have already made the non-prepared statement

<?php
include('includes/config.php');
if(!empty($_POST["catid"])) 
{
 $id=intval($_POST['catid']);
$query=mysqli_query($con,"SELECT * FROM  tblwritter WHERE CategoryId=$id and Is_Active=1");

?>
<option value="">Select Writter</option>
<?php
 while($row=mysqli_fetch_array($query))
 {
  ?>
  <option value="<?php echo htmlentities($row['WritterId']); ?>"><?php echo htmlentities($row['Writter']); ?></option>
  <?php
 }
}

?>
<?php
include('includes/config.php');
if(!empty($_POST["catid"])) 
{

$stmt = $con -> mysqli_query('SELECT * FROM  tblwritter WHERE CategoryId=? and Is_Active=1');

$id=intval($_POST['catid']);

$stmt -> bind_param('i', $id);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($WritterId, $Writter);
$stmt -> fetch();

?>
<option value="">Select Writter</option>
<?php
 while($row=mysqli_fetch_array($stmt))
 {
  ?>
  <option value="<?php echo htmlentities($row['WritterId']); ?>"><?php echo htmlentities($row['Writter']); ?></option>
  <?php
 }
}

The expected results of this code is to show Writters name in a drop down.

Advertisement

Answer

You’re not actually preparing a query. You are assigning the result set of a query to $stmt. Instead, you should write:

$stmt = $con -> prepare('SELECT * FROM  tblwritter WHERE CategoryId=? and Is_Active=1');

Next, you need to use fetch to return data from a prepared statement. You can use it in a loop in the same way as you call mysqli_fetch_array. Remove your first call (as it will consume a row you want to output):

$stmt -> fetch();

and replace the loop starting with:

while($row=mysqli_fetch_array($stmt))

with

while ($stmt->fetch())
{
?>
  <option value="<?php echo htmlentities($WritterId); ?>"><?php echo htmlentities($Writter); ?></option>
<?php
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement