How to fetch data in PHP with MySQLi?

2020-02-01 17:20发布

I tried several times but cannot succeed in getting the right syntax—according to PHP 5.5.12 —to fetch single or multiple rows from my database.

session_start();
$con=mysqli_connect("localhost","root","","doortolearn");
if (!$con) {
    echo "Could not connect to DBMS";       
}
    $query="select * from teacher where tremail='$_POST[email]' and trpasssword='$_POST[password]'";
    $result=mysqli_query($con,$query);
    $flag=FALSE;
    while ($row=mysqli_fetch_array($result,MYSQLI_BOTH)) {
        $_SESSION['email']=$row['email'];
        $flag=TRUE;
    }

标签: php mysqli
3条回答
淡お忘
2楼-- · 2020-02-01 17:55

can You try this code


<?php $query=mysqli_query($connection, "SELECT * FROM user");
while($rows=mysqli_fetch_array($query)){ ?>
<tr>
<td><?php echo $rows['name']; ?></td>
<td><?php echo $rows['age']; ?></td>
<td><?php echo $rows['mobile']; ?></td>
<td><?php echo $rows['email']; ?></td>
</tr>
<?php } ?>
查看更多
一纸荒年 Trace。
3楼-- · 2020-02-01 17:59
$r =$mysqli->query("select * from users");

while ( $row =  $r->fetch_assoc() )
{
?>
  <tr>
  <td><?php echo $i++; ?></td>
  <td><?php echo $row['name']; ?></td>
  <td><?php echo $row['pwd']; ?></td>
  </tr>
  <?php
  }
  ?>
查看更多
倾城 Initia
4楼-- · 2020-02-01 18:04

First, you have no single quotes ' around $_POST[password]:

$query = "SELECT * FROM teacher WHERE tremail='". $_POST['email'] ."' and trpasssword='" . $_POST['password'] . "'";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$flag = FALSE;
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
    $_SESSION['email'] = $row['email'];
    $flag = TRUE;
}

But past that, do you even have a MySQL database connection set here? I see $con but is that really working?

Also, check if there are errors by adding or die(mysql_error($con)) to your mysqli_query($con, $query) line.

Also, you have a $_SESSION value, but do you even set session_start at the beginning of your script?

But I also recommend you use mysqli_stmt_bind_param for your values to at least escape them if you are not going to do basic validation:

$query = "SELECT * FROM teacher WHERE tremail=? and trpasssword=?";
mysqli_stmt_bind_param($query, 'ss', $_POST['email'], $_POST['password']);
$result = mysqli_query($con, $query) or die(mysqli_error($con));
$flag = FALSE;
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
    $_SESSION['email'] = $row['email'];
    $flag = TRUE;
}
查看更多
登录 后发表回答