简体   繁体   中英

PDO mysql query not working

For some reason this query isnt working. It isnt throwing any errors. if i use it in the traditional mysqli. it works.. im trying to convert my sql to pdo.

$conn = new PDO('mysql:dbname=test;host=localhost', 'root', 'root');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$user_id = is_numeric($_SESSION['user_id']) ? $_SESSION['user_id'] : die();
$stmt = $conn->prepare("SELECT * from posts WHERE user_id=:user_id ");
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$i=1;
if ($i=1) {
foreach ($rows as $row) {
if (($row["user_id"])==true){
echo $row["title"];
}  
}

Couple of problems here. First, this...

$user_id = is_numeric($_SESSION['user_id']) ? $_SESSION['user_id'] : die();

is just terrible. I also don't see a session_start() (which may be the actual cause of your problems). Go with something like

session_start();

if (!(isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']))) {
    throw new Exception('Invalid user id in session');
}
$user_id = $_SESSION['user_id'];

Now for your result set iteration...

$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);

foreach ($stmt as $row) { // this is possible because PDOStatement implements Traversable
    echo $row['title'];
}

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