Page 1 of 1

Cookie and MySQL Query

Posted: Tue Apr 06, 2004 8:07 pm
by mike77
Im having a bit of a problem searching a mysql database with a value in a cookie...The cookie is storing the user name as "username" and I would like it to search a table "users" for the results when they match "username"

this is what I have so far:
Admin Edit: Added tags to code for readability.[/color]

Code: Select all

<? $user = $HTTP_COOKIE_VARS["username"];?>

<?php
mysql_select_db($database_etst, $etst);
$query_Recordset1 = "SELECT city FROM users where $user = username ";
$Recordset1 = mysql_query($query_Recordset1, $etst) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Re
cordset1 = mysql_num_rows($Recordset1);
?>

<?php echo $row_Recordset1['user']; ?>
Im assuming the problem lies in the line that begins with "$query_Recordset1" but not sure what should be there...


thanks for help!

Posted: Wed Apr 07, 2004 3:05 am
by twigletmac
Code and comments below:

Code: Select all

<?php

// if you're using PHP version 4.1 or greater then you can use
// $_COOKIE instead of the deprecated $HTTP_COOKIE_VARS
$user = $_COOKIE['username'];

// use error handling on database functions:
@mysql_select_db($database_etst, $etst) or die(mysql_error());

// The SQL statement was a bit foobared - instead of 
// $user = username you should probably have (I don't know as
// I don't have access to your table structure)
// user = $user (or maybe username = $user depending what the
// username field is called):
$sql = "SELECT city FROM users where user = $user";

$result = mysql_query($query_Recordset1, $etst) or die(mysql_error().'<p>'.$sql.'</p>');

// the code you had would give you an error as you aren't 
// selecting the user's name from the database, you are
// selecting the city - you already know the username, 
// you also need to test that a user with that name does
// exist in the database (cookies can be modified)
if (mysql_num_rows($result) == 1) {
	$row = mysql_fetch_assoc($result);

	$city = $row['city'];
	echo $user.' is from '.$city;
} else {
	echo 'That username does not exist.';
}

?>
Mac