I have successfully created a PHP script which connects to my database. When the user types in their email address I want to display some information on the same page from the database relating to that email address. The database fields that I want to display are: name, tracking, status.
My question is how can I display this information. I know I have code at the bottom which redirects to a page if login successful which iI no longer want.
PHP Script:
<?php
$host="######"; // Host name
$username="######"; // Mysql username
$password="######"; // Mysql password
$db_name="######"; // Database name
$tbl_name="orders"; // Table name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$myusername = stripslashes($myusername);
$myusername = mysql_real_escape_string($myusername);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
header("location:trackyourorder.html"); //DO NOT WANT TO REDIRECT
}
else {
echo "Wrong Username";
}
?>
You can use the fetch_row function in combination with a while loop. This is the easiest way. Read more about the function here: http://www.php.net/manual/en/mysqli-result.fetch-row.php
For example:
if ($result = mysqli_query($link, $query)) {
/* fetch associative array and print result*/
while ($row = mysqli_fetch_row($result)) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
If I understand your question correctly, you and asking how to output data from the database directly to the screen. Without offering any formatting, this might be what you are looking for.
$sql="SELECT * FROM $tbl_name WHERE username='$myusername'";
$result=mysql_query($sql);
$results_array=mysql_fetch_array($result);
Once you have the $results_array, you can access any fetched columns from the database using normal keyed array syntax, such as:
echo $results_array["username"];
Hopefully that helps.
As an example:
$result = mysql_query($sql);
if(! $result) die("Error executing query");
while($row = mysql_fetch_assoc($result) {
echo $row["name"];
echo $row["tracking"];
echo $row["status"];
}
Or, you can do it the object oriented way:
$result = mysql_query($sql);
if(! $result) die("Error executing query");
while($row = mysql_fetch_object($result) {
echo $row->name;
echo $row->tracking;
echo $row->status;
}
On a related note, if the only fields you want are name, tracking, and status, you should only select those fields in your query. It will make the query faster, as well as prevent data from being fetched that you don't want (which can be more secure)
"SELECT name, tracking, status FROM $tbl_name WHERE username='$myusername'";
A traditional way from start to finish could be as follows.
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName']; //**Put all your formatting in here!**
echo "<br />";
}
mysqli_close($con);
?>
Related
Yes it connects to the database, everything else works fine. I cant seem to pull the pass from the db its showing no returned echo
<?php
$username="test";
include("db.php");
$con=mysql_connect($server, $db_user, $db_pwd) //connect to the database server
or die ("Could not connect to mysql because ".mysql_error());
mysql_select_db($db_name) //select the database
or die ("Could not select to mysql because ".mysql_error());
$query="select password from ".$table_name." where username='$username'";
$result=mysql_query($query,$con) or die('error');
while ($row = mysql_fetch_assoc($result));
$un_pass_s1=$row['password'];
echo $un_pass_s1;
?>
while ($row = mysql_fetch_assoc($result)); loops until $row is false. The loop body is a single empty statement, ;. You need to put your code which accesses $row inside the loop, not after it.
$sql=mysql_query("select password from ".$table_name." where username='$username'");
while($row=mysql_fetch_array($sql))
{
$un_pass_s1=$row['password'];
}
echo "value=".$un_pass_s1;
i'm going to update a row into mysql database. the senarius is: taking the values from a form and redirect to another file and set the form values to database using update statement. the problem is that mysql_query return value 1 and does not return any error but when i check the database through phpmyadmin my database doesn't affected.
here is the code
<?php
$host="localhost";
$username="root";
$password="";
$db_name="login_takrim";
$tbl_name="takrim_users";
// Connect to server and select databse.
mysql_connect("c$host","$username","$password") or die("can not connect");
mysql_select_db($db_name) or die(mysql_error());
// username and password sent from form
$myusername=$_POST["txtusername"];
$mypassword=$_POST["txtpassword"];
$myemail=$_POST["txtemail"];
// To protect MySQL injection
$myusername=stripslashes($myusername);
$myemail=stripslashes($myemail);
$mypassword=stripslashes($mypassword);
$myemail=mysql_real_escape_string($myemail);
$myusername=mysql_real_escape_string($myusername);
$mypassword=mysql_real_escape_string($mypassword);
echo "$myusername $mypassword $myemail";// test to see i get the form value on the php server.
$sql="UPDATE $tbl_name SET username = '$myusername' and password = '$mypassword' and email= '$myemail' where showname='hussein'";
$result=mysql_query($sql) or die(mysql_error());//does not return error
echo $result;
if($result==false)
{
echo "no";
}
else
{
//header("location:setEmail.php");
echo "yes";
}
?>
query may excuted correctly may be there was no matching records just do like this
<?php
$host="localhost";
$username="root";
$password="";
$db_name="login_takrim";
$tbl_name="takrim_users";
// Connect to server and select databse.
mysql_connect("c$host","$username","$password") or die("can not connect");
mysql_select_db($db_name) or die(mysql_error());
// username and password sent from form
$myusername=$_POST["txtusername"];
$mypassword=$_POST["txtpassword"];
$myemail=$_POST["txtemail"];
// To protect MySQL injection
$myusername=stripslashes($myusername);
$myemail=stripslashes($myemail);
$mypassword=stripslashes($mypassword);
$myemail=mysql_real_escape_string($myemail);
$myusername=mysql_real_escape_string($myusername);
$mypassword=mysql_real_escape_string($mypassword);
echo "$myusername $mypassword $myemail";// test to see i get the form value on the php server.
$sql="UPDATE $tbl_name SET username = '$myusername', password = '$mypassword',email= '$myemail' where showname='hussein'";
$result=mysql_query($sql) or die(mysql_error());//does not return error
if(mysql_num_rows($result) > 0)
{
//header("location:setEmail.php");
echo "yes";
}
else
{
echo "no";
}
?>
Chage your UPDATE statement like this
$sql="UPDATE $tbl_name SET `username` = '$myusername',`password` = '$mypassword',`email`= '$myemail' where `showname`='hussein'";
Disclaimer: Stop using mysql_* functions as they are deprecated. Switch to MySQLi or PDO instead.
You have an extra c here (before $host):
mysql_connect("c$host","$username","$password") or die("can not connect");
I have the following code running on my website. I call it from a html form. The form has a client number which looks up the redirect value in the database and should redirect to the website. The redirect works great with one value in the database. However, when I add more values it uses the last one. I added the echo goto so I can see. The script pulls every redirect value for the whole database. How can I just pull the redirect value associated with the client_number?
<php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="clients"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// sent from form
$myclient=$_POST['myclient'];
$myclient = stripslashes($myclient);
$sql="SELECT * FROM $tbl_name WHERE client_number='$myclient'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
$result = mysql_query("SELECT redirect FROM clients");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$goto = $row['redirect'];
//added to see output
echo $goto;
//header ("location: $goto");
}
exit();
}
else {
echo "Account number is invalid";
}
?>
From your query you are pulling all redirect
$result = mysql_query("SELECT redirect FROM clients");
which should be
$result = mysql_query("SELECT redirect FROM clients WHERE clientID=1234");
Then you were using while instead of if
if($row = mysql_fetch_array($result, MYSQL_ASSOC)) { }
Using header('Location: xyz.ext') redirect in loop is bad
I have been trying to make a user login page that, when the user logs in, will redirect a user based on the user id to a specific url.
To be more specific, let's say in the database I have 4 rows: id, username, password, redirect. After successful login it will go to a user's specific row, grab the redirect url, and redirect the user to that url. I have made a script that will redirect the url based on the database's redirect url, but when I add more users to the db it freezes and often does not display anything or redirects to the wrong url. Here is the code:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file"login_success.php"
$_SESSION['username'] = $myusername;
$_SESSION['password'] = $mypassword;
$result = mysql_query("SELECT redirect FROM members");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
header("Location: " . $row['redirect']);
}
exit();
}
else {
echo "Wrong Username or Password";
}
?>
I really appreciate any help, tutorials, or criticism. Thank you.
(Please also be descriptive in your answers I am still pretty new to web development. ;) )
Since you can only redirect a person one time, and you already have the redirect value from your original select query that checked for a username and password match, I would change your code to something like this:
$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1){
// Register $myusername, $mypassword and redirect to file"login_success.php"
$_SESSION['username'] = $myusername;
$_SESSION['password'] = $mypassword;
$result = mysql_fetch_array($result); // get the result set from the query
$redirect = trim($result['redirect']); // get the redirect column's value
if ($redirect == '') {
echo "No redirect value was set!";
} else {
header('Location: ' . $redirect);
exit;
}
} else {
echo "Wrong Username or Password";
}
$result = mysql_query("SELECT redirect FROM members");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
header("Location: " . $row['redirect']);
}
exit();
I would start at line one. This query says pull redirect for all rows in the members table. After that you run in to a loop where you are trying to redirect to every value.
I have the below code that i am wanting to into certain files so that when someone visits this "certain" file they get banned if they are not allready. but for some reason it is not adding new visitors into the database, if i add a user manually it works fine and echo's Banned! but otherwise it just echo's the $sql query but does not actually do it.
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="banlist"; // Database name
$tbl_name="list"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$sql="SELECT * FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count==0){
$sql="INSERT INTO $tbl_name (`id` ,`ip`) VALUES (NULL , $ip)";
mysql_query($sql);
echo $sql;
//header("location:index.html");
} else {
// Register $myusername, $mypassword and redirect to file "login_success.php"
//header("location:index.html");
echo "banned!";
exit();
}
?>
Have you double-checked that your MySQL account has the INSERT privilege?
You'll also find that things go more smoothly if you always check the return value of mysql_query(). While you're developing, you could change these lines (from the end of your snippet):
mysql_query($sql);
echo $sql;
... to this:
$result = mysql_query($sql);
if($result === FALSE) {
echo 'INSERT failed with this error: '.mysql_error();
} else {
echo 'INSERT succeeded';
}
Also if you're not yet familiar with SQL injection, you'll want to become familiar with it. Your code is currently vulnerable to this kind of attack, because it doesn't filter input (the HTTP headers where you're looking for an IP address) and it doesn't escape output (the variable portion of your dynamically-constructed SQL queries).
just few remarks
$sql="SELECT * FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
wouldn't be better to do a
$sql="SELECT count(*) FROM $tbl_name WHERE ip='$ip'";
$result=mysql_query($sql);
since you don't use that data.
$sql="INSERT INTO $tbl_name (`id` ,`ip`) VALUES (NULL , '$ip')";
mysql_query($sql);
if your id is an auto increment you don't have to include it
$sql="INSERT INTO $tbl_name (`ip`) VALUES ('$ip')";
mysql_query($sql);
You should quote $ip since it's probably a varchar in your table.
Since an ip address should be a sort of unique identifier you have better to use the IP as primary key.
last point checking for results of mysql_query would be a good pratice, like there
$sql="INSERT INTO $tbl_name (`ip`) VALUES ($ip)";
$ret = mysql_query($sql);
if (!$ret) {
die('Invalid query: ' . mysql_error());
}
I think it would give you valuable information about what is happening. in that case it would probably say you have an error near the IP address (because of the missing quotes).