I have a "Windows Apache MySQL PHP" server on my laptop. I get absolutely no error messages, but when I send things to MySQL via PHP script, nothing happens in MySQL (I also sent something via the MySQL command prompt and it looks like it just made a test table and didn't put anything in it like I asked, but I'm not positive I did everything I should have in this case). I've rescripted my whole page a different way and it still doesn't work.
Here is a picture of my form and how the table looks in MySQL:
System:
Windows 7 Home Premium SP1 64 bit--
Apache 2.4.4 32 bit with ssl0.9.8--
PHP 5.4.11 32 bit VC9--
MySQL 5.5.31 64 bit with Navicat Lite
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'projectedin');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " .mysql_error());
function NewUser()
{
$userName = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$password = $_POST['password'];
$birthday = $_POST['birthday'];
$gender = $_POST['gender'];
$query = "INSERT INTO users (username,firstname,lastname,password,birthday,gender) VALUES ('$username','$firstname','$lastname','$password','$birthday','$gender')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED...";
}
}
function SignUp()
{
if(!empty($_POST['username'])) //checking the 'user' name which is from Sign-Up.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM users WHERE username = '$_POST[username]' AND password = '$_POST[password]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
newuser();
}
else
{
echo "SORRY...YOU ARE ALREADY REGISTERED USER...";
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
mysqli_close ($con);
?>
There are a number of concerns here (more on that later), but this might be an issue for you:
You try to call your new user function like this:
newuser();
However it is named NewUser. This is case sensitive and will not work. Look at your error logs to see the errrs you are getting here.
Other issues:
You are using deprecated mysql_* functions. If you are learning PHP, learn the right way and use mysqli or PDO.
You are not escaping your input at all, and are therefore very prone to SQL injection attacks.
You are kind of randomly using functions when they don't really bring you any value.
You are kind of going outside of typical PHP coding standard when having your function names start with uppercase letter. This is a bit unusual for PHP, though this would actually work.
You have an error in your Signup query:
$query = mysql_query("SELECT * FROM users WHERE username = '$_POST['username']' AND password = '$_POST['password']'") or die(mysql_error());
I changed $_POST[username] to $_POST['username'] and $_POST[password] to $_POST['password']
Also, you are vulnerable for MySQL injections, you should use mysql_real_scape_string function to clean each $_POST var: $userName = mysql_real_scape_string($_POST['username']);
Finally, you should not use mysql* functions, they are deprecated.
Related
I'm trying to convert some php code that uses mysql into mysqli code. I'm not sure why it doesn't work - I didn't write the original code and am not that comfortable with the hash part of it, and it seems to be where the issue is. As I show in the code below, the "error" part gets echo'ed so it's something to do with the hash strings, but I don't really understand why changing to mysqli has broken the code. Both versions of the code are below, and the original code works. I deleted the variables (host name, etc.) but otherwise this is the code I am working with.
Mysql Code:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysql_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysql_connect_error());
mysql_select_db($db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysql_real_escape_string($_GET['name'], $db_link);
$score = mysql_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "insert into scores values (NULL, '$name', '$score');";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
}
Mysqli code (doesn't work):
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysqli_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysqli_connect_error());
mysqli_select_db($db_link, $db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysqli_real_escape_string($_GET['name'], $db_link);
$score = mysqli_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "INSERT INTO `scores` VALUES (NULL, '$name', '$score');";
$result = mysqli_query($db_link, $query) or die('Query failed: ' . mysqli_error($db_link));
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
mysqli_close($db_link); //close the database connection
One notable "gotchu" is that the argument order is not the same between mysql_real_escape_string and mysqli_real_escape_string, so you need to swap those arguments in your conversion.
$name = mysqli_real_escape_string($db_link, $_GET['name']);
$score = mysqli_real_escape_string($db_link, $_GET['score']);
It's good that you're taking the time to convert, though do convert fully to the object-oriented interface if mysqli is what you want to use:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
// Enable exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli($host_name, $user_name, $password);
$db->select_db($db_name);
return $db;
}
$db = db_connect(""); //connect to the database using db_connect function
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $_GET['hash']) {
// Don't include ; inside queries run through PHP, that's only
// necessary when using interactive MySQL shells.
// Specify the columns you're inserting into, don't leave them ambiguous
// ALWAYS use prepared statements with placeholder values
$stmt = $db->prepare("INSERT INTO `scores` (name, score) VALUES (?, ?)");
$stmt->bind_param("ss", $_GET['name'], $_GET['score']);
$result = $stmt->execute();
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
// Should use a connection pool here
$db->close();
The key here is to use prepared statements with placeholder values and to always specify which columns you're actually inserting into. You don't want a minor schema change to completely break your code.
The first step to solving a complex problem is to eliminate all of the mess from the solution so the mistakes become more obvious.
The last if statement is controlling whether the mysql query gets run or not. Since you say this script is echoing "error" form the else portion of that statement, it looks like the hashes don't match.
The $hash variable is getting passed in on the URL string in $_GET['hash']. I suggest echo'ing $_GET['hash'] and $real_hash (after its computed by the call to MD5) and verify that they're not identical strings.
My hunch is that the $secretKey value doesn't match the key that's being used to generate the hash that's passed in in $_GET['hash']. As the comment there hints at, the $secretKey value has to match the value that's used in the Javascript, or the hashes won't match.
Also, you may find that there's a difference in Javascript's md5 implementation compared to PHP's. They may be encoding the same input but are returning slightly different hashes.
Edit: It could also be a character encoding difference between Javascript and PHP, so the input strings are seen as different (thus generating different hashes). See: identical md5 for JS and PHP and Generate the same MD5 using javascript and PHP.
You're also using the values of $name and $score after they've been escaped though mysqli_real_string_escape, so I'd suggest making sure Javascript portion is handling that escaping as well (so the input strings match) and that the msqli escape function is still behaving identically to the previous version. I'd suggest echo'ing the values of $name and $score and make sure they match what the Javascript side is using too. If you're running the newer code on a different server, you may need to set the character set to match the old server. See the "default character set" warning at http://php.net/manual/en/mysqli.real-escape-string.php.
This question already has answers here:
How do I get PHP errors to display?
(27 answers)
Closed 5 years ago.
<?php
//Get Value
$username = $_POST['user'];
$password = $_POST['pass'];
//Connet To The Server And Select Database
mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
mysqli_select_db("xxxxx");
//Query The Database For User
$result = mysqli_query("select * from user where username = '$username' and password = '$password'")
or die("Failed to query database ".mysqli_connect_error());
$row = mysqli_fetch_array($result);
if (empty($username)) {
header('Location: fa.html');
} elseif (empty($password)) {
header('Location: fa.html');
} elseif ($row['username'] == $username && $row['password'] == $password){
header('Location: su.html');
} else{
header('Location: fa.html');
}
?>
I have no experience to code PHP so i have no idea what's wrong is my code.
I have replace "mysql" into "mysqli" but it is still not working correctly.
It's work fine when running "mysql_*" and using my local Window web server.
But when i put it into Linux server it occur error message "Failed to query database ".
Add the fourth parameter here as database name like
mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx", "database_name");
and remove
mysqli_select_db("xxxxx");
A sample way of writing php code would be
$link = mysqli_connect("server_name","username","password","database_name");
if(mysqli_connect_error()) {
die("There was an error connecting to the database");
}
$query = 'yourQuery';
$result=mysqli_query($link,$query);
if ( false==$result ) {
printf("error: %s\n", mysqli_error($link));
}
This will work
Hope it helps
You need to trap for more errors to see where it's failing. Right now all you know is that it's failing at-least by the mysqli_query() line where you do trap for errors.
First you have to ensure that you can actually connect to the database server.
Change:
mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxxxxx");
to
if(!mysqli_connect("192.168.xxx.xxx", "xxx", "xxxxxxxxxx"))
{
die("Could not connect");
}
then you should also trap for errors on selecting the database. Change:
mysqli_select_db("xxxxx");
to
if(!mysqli_select_db("xxxx"))
{
die("Could not select database");
}
Edit: Also you really didn't need to blank-out your IP. 192.168.1.* is a class C private address - meaning it is not accessible from outside your local network.
You need to learn more, because these are really just the basics. The reason why your code works locally and doesn't on the remote server is probably caused by your DB access - it obviously isn't the same. You need to change your credentials and your db IP to match your remote server if you want to deploy your code there.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So trying to insert some data from a PHP page into my SQL database. This page is ONLY accessible via myself so I'm not worried about it being accessed or SQL injectable etc. My issue is no matter what code I use it doesn't go into the database. I've tried coding it myself, using template codes, taking from php.net etc nothing has worked!
It now redirects me with the success message but still nothing in the database.
Code will be put below and I'll edit some of my details for privacy reasons.
<?php
require connect.php
// If the values are posted, insert them into the database.
if (isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$isadminB = $_POST['isadmin'];
$password = $_POST['password'];
$query = "INSERT INTO `users` (user_name, password, isadmin) VALUES ('$username', '$password', '$isadminB')";
$result = mysql_query($query);
if($result){
$msg = "User Created Successfully.";
}
}
$link = mysql_connect("localhost", "root", "password");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
The echo mysql_errno($link) . ": " . mysql_error($link). "\n"; was the code that gave me error code 0?
As requested the code for the form from my previous page.
<form action="account_create_submit.php" method="post">
Username: <input type="text" name="username" id="username"> <br /><br />
Password: <input type="password" name="password" id="password"> <br /><br />
<span id="isadmin">Is Admin: Yes<input type="radio" name="isadmin" id="1" value="1"> | No<input type="radio" name="isadmin" id="0" value="0"><br /></span>
<span id="submit"><input type="submit" value="Create Account"></span>
</form>
Ok so changed the form code so method is now POST. Great! All data is being read correctly although that wasn't my issue as even typing in hard data for the code to submit wasn't working at least its a future issue resolved already. The new error code is no longer 0 but rather the following:
1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user_name', 'password', 'isadmin') VALUES ('testZ', 'lol', '1')' at line 1
Connect.php
<?php
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('Default_DB');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
Firstly, for those of you getting the misconception about password for a column name:
Sure, it's MySQL "keyword", but not a "reserved" word; more specifically, it is a function (see ref). Notice there is no (R) next to the "function (keyword) name": https://dev.mysql.com/doc/refman/5.5/en/keywords.html therefore it's perfectly valid as a column name.
Ref: https://dev.mysql.com/doc/refman/5.1/en/encryption-functions.html#function_password
Ticks are only required if it is used in order to prevent it from being recognized as a "function", which it clearly is not in the OP's case. So, get your information and facts straight.
More specifically, if a table named as PASSWORD and without spaces between the table name and the column declaration:
I.e.: INSERT INTO PASSWORD(col_a, col_b, col_c) VALUES ('var_a', 'var_b', 'var_c')
which would throw a syntax error, since the table name is considered as being a function.
Therefore, the proper syntax would need to read as
INSERT INTO `PASSWORD` (col_a, col_b, col_c) VALUES ('var_a', 'var_b', 'var_c')
(Edit:) To answer the present question; you're using $connection in your connection, but querying with $link along with the missing db variables passed to your query and the quotes/semi-colon I've already outlined here.
That's if you want to get that code of yours going, but I highly discourage it. You're using a deprecated MySQL library and MD5 as you stated. All old technology that is no longer safe to be used, nor will it be supported in future PHP releases.
You're missing a semi-colon here require connect.php and quotes.
That should read as require "connect.php";
You should also remove this:
$link = mysql_connect("localhost", "root", "password");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
you're already trying to include a connection file.
Use this in your connection file: (modified, using connection variable connection parameter)
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('Default_DB', $connection);
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
and pass the $connection to your query as the 2nd parameter.
$result = mysql_query($query, $connection);
Add error reporting to the top of your file(s) right after your opening PHP tag
for example <?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything.
Also add or die(mysql_error()) to mysql_query().
If that still gives you a hard time, you will need to escape your data.
I.e.:
$username = mysql_real_escape_string($_POST['username'], $connection);
and do the same for the others.
Use a safer method: (originally posted answer)
May as well just do a total rewrite and using mysqli_ with prepared statements.
Fill in the credentials for your own.
Sidenote: You may have to replace the last s for an i for the $isadminB that's IF that column is an int.
$link = new mysqli('localhost', 'root', 'password', 'demo');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
if (!empty($_POST['username']) && !empty($_POST['password'])){
$username = $_POST['username'];
$isadminB = $_POST['isadmin'];
$password = $_POST['password'];
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `users`
(`user_name`, `password`, `isadmin`)
VALUES (?, ?, ?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('sss', $username, $password, $isadminB);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
}
else{
echo "Nothing is set, or something is empty.";
}
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
You can also use this PDO example pulled from one of ircmaxell's answers:
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You are using "get" as your form submission method. "post" variables won't be recognized.
Also...
It looks like you're missing the second parameter of your mysql_query() function which is your link identifier to the MySQL connection. I'm assuming you've created the connection in connection.php.
Typically, the mysql_query() function would be
$result = mysql_query($query, $conn);
with $conn having been pre-defined in your connection.php file.
password is a special word in MySQL, and it might be necessary to put the word in quotes like `password`.
Why are you putting all the information from the form in the link on submit? ex: account_create_submit.php?username=myusername&password=mypassword&isadmin=0
I can see that $username = $_POST['username']; doesn't match the username in your query string.
$query = "INSERT INTOusers(user_name, password, isadmin) VALUES ('$username', '$password', '$isadminB')";
While your fixing that why don't you just make $isadminB and $_POST['isadmin'] the same. Use 'isadminB' in both places.
Check that out and see what happens!
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I'm currently trying to create a php file that can verfify a user's input on user and pass against a sql database and bring back a response to the user...via website. But I keep getting this error:
Parse error: syntax error, unexpected '$row' (T_VARIABLE) in /srv/disk7/1855095/www/hmfs.dx.am/index.php on line 24
<?php
define('DB_HOST', 'localhost');
define('DB_HOST', 'practice');
define('DB_HOST', 'root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn()
{
session_start(); //starting the session for user profile page
if(!empty($_POST['user']))
//checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$query = mysql_query("SELECT * FROM UserName
where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query)
if(!empty($row['userName']) AND !empty($row['pass']))
{
$_SESSION['userName'] $row['pass'];
echo "SUCESSFULLY OGIN TO USER PROFILE PAGE...";
}
else
}
echo "SORRY...YOU ENTERED THE WRONG ID AND PASSWORD...PLEASE RETRY...";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
Any help? :(
your error message says to look at line 24, in which you find this:
$_SESSION['userName'] $row['pass'];
which isn't a valid statement. It should probably be
$_SESSION['userName'] = $row['pass'];
although I would not store a password in a session (session data might be stored in a shared temporary directory).
Please also note that your code is extremely vulnerable to SQL injection. Read up on prepared statements, and don't use mysql_ which is deprecated since 2013. Use mysqli_ or PDO instead.
Additionally, for real-world code, you should hash your passwords when storing them.
Here are some tips
1)Don't use mysql. It's deprecated and very vulnerable. Use Mysqli or PDO instead.
2)Never check a password in the query itself. Because in your code if I enter your username and ' OR 1=1 as my password I will login in your account. Select by username then check the password via PHP
3) your error is because of a missing ; at the end of $row = mysql_fetch_array($query) or because of a missing = between $_SESSION['userName'] and $row['pass'];
Change
$_SESSION['userName'] $row['pass'];
To
$_SESSION['userName'] = $row['pass'];
It quite simple
you've forgotten to use semicolon after $_SESSION['userName']
I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.