简体   繁体   中英

Get result from more than one colum MySQL PHP

I am trying to get the results from two MySQL columns with PHP, but I can only retrieve one.

Below is my code.

    $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $dbh->prepare("SELECT user_id, Email, User_Password, twitter FROM user_detail WHERE Email = :Email );


    $stmt->bindParam(':Email', $Email, PDO::PARAM_STR);

    $stmt->execute();

    $user_id = $stmt->fetchColumn();
    $twitter = $stmt->fetchColumn();

PDOStatement::fetch I guess ?

$stmt->execute();
if($row = $stmt->fetch()) {
   $user_id = $row['name'];
   $twitter = $row['twitter'];
}
<?php
$stmt->execute();
$datas = $stmt->fetchAll();

foreach($datas as $d) {
    echo $d['user_id']. '<br>';
    echo $d['Email']. '<br>';

    print_r($d); 
}

It will help you to understand how this work I think, print_r will show you the array of the current item, each element is accessible by $d[key];

  1. You forgot to close a double-quote on the prepare() line.
  2. use fetchAll() instead of fetchColumn()

fetchColumn() - Returns a single column from the next row of a result set or FALSE if there are no more rows.

fetchAll() - Returns an array containing all of the result set rows.

Since you already specified which columns to select in your SELECT statement, performing fetchAll() is perfect for what you're trying to achieve.

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