Jump to content

mysql_fetch_assoc question and array key question


silverglade

Recommended Posts

Hi, I am trying to understand the code below, I have commented on the lines my questions. Any help greatly appreciated. Thank you.

 

:)

 

 

<?
require_once('globals.php');
session_start();
if (!isset($_SESSION['myusername']))
{
header('Location: checklogin.php');
}

$query = "SELECT id FROM users";//stores the sql commands in query as a string.
   
// Perform Query
$result = mysql_query($query);//query to the database using sql commands, hold 'id' row field in $result. 

$row = mysql_fetch_assoc($result);// WHAT ARE THE KEYS FOR THIS ASSOCIATIVE ARRAY?
$_SESSION['current_id'] = $row['id'];  //NEEDS TO BE IS FOR CURRENT USER, HOW DO WE KNOW THIS IS THE //ID FOR CURRENT LOGGED IN USER?
?>

First question, since it is an associative array, the keys will be the field names of the table that mysql_query() retrieved.

Since the sql selects only the id, the only available key will be "id" which is where you get $row['id'] from.

 

Second question, really you dont know if the $row['id'] is the id of the current user, and more than likely it won't be, it will be the first id i the table. Depending on how you have you table set up, you can most likely use a WHERE statement in your query and use $_SESSION['myusername']...

$username = $_SESSION['myusername'];
$query = "SELECT id FROM users WHERE username = '$username'";//assumes that you have a field called username
   
// Perform Query
$result = mysql_query($query);//query to the database using sql commands, hold 'id' row field in $result. 

$row = mysql_fetch_assoc($result);
$_SESSION['current_id'] = $row['id'];  
?>

Awesome thank you very much for that code, that makes sense to me, I wish I could have thought of it. Also, I got this code from an administrator. But thanks for the working code and both of you explaining to me about the keys. Also, is there a way I can learn to come up with these things like you can? I am forever coming on the forum because I am unable to come up with the answers myself. How exactly did you learn to be able to code on your own without the help of the forum?

 

Please I need to know EXACTLY what you both did so I can follow it exactly. I try so hard to come up with it, even with pseudocode, but I failed with several different problems. I am going to post my other problem in this thread as well. I think then I will have a functioning gallery with users attached. awesome. :) :) :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.