Jump to content

retrieving value from MySQL DB,then storing as a Session var


webguync

Recommended Posts

I need some help with this. A user fills out a form, one of the fields is a zip code field. I need to retrieve that value from MySQL store as a session var and set that value as a variable to use with a weather display API. The ID is being stored from the form page.

 

Here is what I have so far, after the values are submitted into the DB.

 

<?php
session_start();
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Profile WHERE id='{$_SESSION['id']}");

while ($row = mysql_fetch_assoc($result)) {
    $_SESSION['id'] = $row['id'];
$_SESSION['zip'] = $row['zip'];

}


mysql_close($con);
?>

 

and then for the weather API, I need to set the stored variable to something

$zip = 'stored zip code value'; 

$_SESSION['zip'] = '';
$result = mysql_query("SELECT * FROM Profile WHERE id='{$_SESSION['id']}");
if (mysql_numrows($result) > 0) {
    $row = mysql_fetch_assoc($result);
    $_SESSION['zip'] = $row['zip'];	
}


// Later....
$zip = $_SESSION['zip'];

hmm, why would I be getting this warning?

Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in/new_site/Weather/weather.php on line 35

 

which is this part

$_SESSION['zip'] = '';
$result = mysql_query("SELECT * FROM Profile WHERE id='{$_SESSION['id']}");
if (mysql_numrows($result) > 0) {
    $row = mysql_fetch_assoc($result);
    $_SESSION['zip'] = $row['zip'];   
}

You haven't checked that $result is a resource. If your query fails (which it must be) $result will be the boolean false, not a resource which is what mysql_num_rows expects.

 

Always check variables are what you expect them to be before using them.

No your query is failing due to an error.

 

A query that executes successfully but matches zero rows is a successful query and does not produce errors when you access the result set (unless you use mysql_result(), which has the misfortune of producing an error when there are zero rows in the result set.)

 

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.