Click to See Complete Forum and Search --> : mysql_result problem?


k0r54
03-15-2005, 12:12 PM
Hi,

I am using this code to get my row back, but my config file can have errors on or off so i have made this and now how do I actually get the result of ID


$sql_query2 = "SELECT ID FROM ".DATABASE_PREFIX."users WHERE Username = '$_POST[U_Username]' LIMIT 1";

if (!@mysql_query($sql_query2, $sql_id)) {

if (SQL_SHOW_ERRORS == "true") SamePageErrorMsg("mysql_insert", $sql_id);
} else {

$USER_ID = mysql_result(???);
}


Thanks
Adam

mitcon
03-15-2005, 01:02 PM
The first thing you need to do is to assign the results of your mysql_query command to your variable $mysql_result. The mysql_query command returns a resource (containing the rows from the query command). Your next step is to then process that resource with a while or foreach block.

Here is the sample code from the PHP manual at www.php.net (http://www.php.net) I lay no claim to producing this code...

<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';

// Formulate Query
// This is the best way to perform a SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));

// Perform Query
$result = mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}

// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>

Take a close look at the mysql_real_escape_string() function used in the select string. It is a good technique to use for security's sake (search for articles on "SQL Injection", I believe it is called).

This example shows how to process multiple rows in the $return resource. You can apply it to your situation. I think this will get you going...be sure to check out http://www.php.net. There are examples like this for almost any PHP command.