简体   繁体   中英

PHP/MySQL - Geting a row from a DB

Can someone help me with my script? It's supposed to read the user's session's member_id , find the corresponding row and echo it out. But when it runs, it outputs nothing.

<?php

//Start session
session_start();

//Make sure user is logged in
require_once('auth.php');

//Include database connection details
require_once('config.php');

//Connect to DB
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}

//Create Querys
$query = "SELECT * FROM stats WHERE member_id='" . $_SESSION['SESS_MEMBER_ID'] . "' "; 
$result = mysql_query($query);

//Gather the whole row into an array
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
{
    echo $row;     
} 

?>

Drop a echo mysql_num_rows($result); immediately after the mysql_query line, and see if you've any results returned from the query - I suspect you'll find you haven't, in which case the SESS_MEMBER_ID is not present in the stats table.

  1. Use PDO instead of mysql_*() functions
  2. $row is an array so echoing it is pointless: PHP arrays , var_dump()
  3. Make sure that SQL query returns anything. Maybe $_SESSION['SESS_MEMBER_ID'] has got some unexpected value?
  4. Do the basic debugging whenever something goes wrong - dump everything:

     var_dump($query); var_dump($result); var_dump($_SESSION); 

    Or even better: use a real debugger.

  5. Make sure that every possible error is displayed - PHP is a very strange language that accepts tones of errors and still can work:

     error_reporting(-1); ini_set('display_errors', 'on'); 

btw: What's the point of SESS_ prefix for session variables?

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