Page 1 of 1
newbie problem: mysql query
Posted: Sun May 18, 2003 11:19 pm
by guycrossley
Hi all!
trying to debug a record insertion form for my blog page.
What i want to happen is:
-User Enters their Nickname into a form
-Then I determine the User Id based on this nickname (since they are both in the 'users' table)
-Insert the blog with user id to the 'posts' table
Pretty simple eh? So what am i doing wrong?
Code: Select all
<?php
$username = $HTTP_POST_VARS['nickname'];
$query_1 = "SELECT USER_ID FROM users WHERE NICK_NAME = $username";
$userid = mysql_query($query_1);
?>
Note that $userid is a number. If i manually set $userid = 4, my insertion code (not shown) works great. The problem is that $userid is not being set to a valid integer, infact it remains NULL... Whats happening!
Thx in advance!

Re: newbie problem: mysql query
Posted: Mon May 19, 2003 3:05 am
by Tubbietoeter
guycrossley wrote:Hi all!
trying to debug a record insertion form for my blog page.
What i want to happen is:
-User Enters their Nickname into a form
-Then I determine the User Id based on this nickname (since they are both in the 'users' table)
-Insert the blog with user id to the 'posts' table
Pretty simple eh? So what am i doing wrong?
Code: Select all
<?php
$username = $HTTP_POST_VARS['nickname'];
$query_1 = "SELECT USER_ID FROM users WHERE NICK_NAME = $username";
$userid = mysql_query($query_1);
?>
Note that $userid is a number. If i manually set $userid = 4, my insertion code (not shown) works great. The problem is that $userid is not being set to a valid integer, infact it remains NULL... Whats happening!
Thx in advance!

Try:
Code: Select all
<?php
$username = $HTTP_POST_VARS['nickname'];
$query_1 = "SELECT USER_ID FROM users WHERE NICK_NAME = '".$username."'";
$userid = mysql_query($query_1);
?>
SQL wants single quotes around varchar thingies.
Also try to output the statement and try it directly onto the database. If this works, you might be using the mysql functions incorrectly.
Posted: Mon May 19, 2003 10:37 am
by McGruff
mysql_query() performs a db query and returns a result resource. A result resource is not a var or array: to fetch data from the resource you would:
$result = mysql_fetch_row($query); // a numerical array
OR:
$result = mysql_fetch_assoc($query); // an associative array
OR:
$result = mysql_fetch_array($query); // both keys
Try this:
Code: Select all
<?php
$username = $HTTP_POST_VARS['nickname'];
// db query
$mysql = "SELECT USER_ID FROM users WHERE NICK_NAME ='" . $username . "'";
$query = mysql_query($mysql) OR die('Cannot query the database <br />' . mysql_error());
// fetch array from the result resource
$result = mysql_fetch_array($query);
// declare var: keys are db column names
$userid = $result['USER_ID'];
?>
Note I've changed the var names slightly to the standard ones (well the ones I'm used to) to avoid confusion.
You may need to addslash $username to match with escaped text in the db.