Having problem with the following code:
<?php
$con = mysql_connect("localhost","","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("abc", $con);
$ids = intval($_GET['id']);
if ($ids==0){
$id = rand (0,50);
header("Location: http://index.php?id=$id");
}
?>
<html>
<body>
<?php
$result = mysql_query("SELECT * FROM abcdatabase WHERE id = '$id'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_array($result);
echo "{$row['username']}<br>";
?>
</body>
</html>
After redirecting to a new page, such as http://index.php/?id=38
, MySQL database is not loading I think. Because the line echo "{$row['username']}<br>";
not displaying anything and also not showing any error message. Actually I'm not understanding what is the wrong I'm making. I'm a novice programmer. Anyone please help me to come up with the issue.
You could try something like this
$id = rand(0, 50);
if (isset($_GET['id'])){
$id = intval($_GET['id']);
}
You should also at least escape the id-variable before inserting it into a SQL query, using
$escapedId = mysql_real_escape_string($id);
For starters you shouldn't use the mysql library anymore because it's deprecated. Use mysqli library instead: http://php.net/manual/en/book.mysqli.php
Secondly you have a little bug. In line 8 you set the $ids variable but in line 19 you don't use it. You use $id there, which would be empty. So you search for id = empty and your query succeeds (you have a result: no records found) so no error message, but you also don't get a name (because no records found). So replace
$result = mysql_query("SELECT * FROM abcdatabase WHERE id = '$id'");
with
$result = mysql_query("SELECT * FROM abcdatabase WHERE id = '$ids'");
In general, if your code expects to find 1 result, also add a check that you really find one and add an error message if you don't. Replace
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
with
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
elseif (mysql_num_rows($result) <> 1) {
echo 'No records found';
exit;
}
Thirdly, there's the header bug like Joachim explained.