PHP and mysql query to retrieve name - php

I have the following code which gets a users data from a table based on their log in details
//==========================================
// CONNECT TO THE LOCAL DATABASE
//==========================================
$user_name = "xxxx";
$pass_word = "xxxxx";
$database = "xxxx";
$server = "xxxxxx";
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM students WHERE L1 = '$uname' AND L2 = '" .md5 ($_POST['password'])."'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
//====================================================
// CHECK TO SEE IF THE $result VARIABLE IS TRUE
//====================================================
if ($result) {
if ($num_rows > 0) {
$color="1";
$result = mysql_query("SELECT * FROM entry, students WHERE entry.studentName = students.studentName AND students.L1='$uname' ") or die(mysql_error());
echo "<p>Welcome "; echo $row[studentName];
echo "<p>You records as of ";
echo date('l jS \of F Y h:i:s A');
echo "<table border='1' cellpadding='2' cellspacing='0'>";
echo "<tr> <th>Date</th><th>Student Name</th> <th>Tutor name</th> <th>Procedure name</th> <th>Grade</th><th>Student Reflection</th><th>Tutor Comments</th><th>Professionalism</th> <th>Communication</th> <th>Alert</th> <th>Dispute</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
if($color==1){
echo "<tr bgcolor=#DDD ><td>".$row['date']."</td><td>".$row['studentName']."</td><td>".$row['tutorName']."</td><td>".$row['procedureName']."</td><td>".$row['grade']."</td><td>".$row['studentReflection']."</td><td>".$row['tutorComments']."</td><td>".$row['professionalism']."</td><td>".$row['communication']."</td><td>".$row['alert']."</td><td>".$row['dispute']."</td></tr>";
// Set $color==2, for switching to other color
$color="2";
}
// When $color not equal 1, use this table row color
else {
echo "<tr bgcolor='#CCC'><td>".$row['date']."</td><td>".$row['studentName']."</td><td>".$row['tutorName']."</td><td>".$row['procedureName']."</td><td>".$row['grade']."</td><td>".$row['studentReflection']."</td><td>".$row['tutorComments']."</td><td>".$row['professionalism']."</td><td>".$row['communication']."</td><td>".$row['alert']."</td><td>".$row['dispute']."</td></tr>";
// Set $color back to 1
$color="1";
}
}
echo '</table>';
}
What I want to do it is echo or print out the users name above the table but I am having difficulty doing so. The only want I can get it it to work is to add it to the while loop but then it prints it out as many times as the user has records.
Can you help?

You will need to fetch the first row in order to gain access to the user information. That means you will have to call mysql_fetch_array once before the loop.
That will get you in trouble, because you will also need to call it in the loop. You could hack around that by using all kinds of boolean flags or copies of the row, but the best way is to change the structure of your code a little.
Use a do-while loop, combined with an if statement. This allows you to fetch a single row first, and take special action if none is found. After that, you got a loop that does what it does now, only it checks if there is a next row after the iteration instead of before, otherwise the first row would be skipped in the table output.
if ($row = mysql_fetch_array( $result )) {
// Print user info
// Print table header
do {
// Print table row
} while ($row = mysql_fetch_array( $result ));
// Print table footer
}
else
{
// User not found. Print error or whatever.
}

You have mistake at your logic...
You are making table of studens and you want to echo Welcome to the student which is logged_in
But you use echo "<p>Welcome "; echo $row[studentName];
Where $row is not set... This name should come from a previous select ..

Related

Shows Table and Values Using Drop Down

In this application I have a drop down so you can select what table you want to view. Using Ajax I push the variable $tbl as an integer and the code below prints out the table that corresponds with that integer. Something is not working though and I need an extra pair of eyes to help debug.
if($tbl == 9){$table = "person";}
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$query = mysqli_query($conn, "SELECT * FROM $table ") or die(mysqli_error($conn));
if($query){
echo '<table border="1"><thead><tr>';
$colnames = array();
while ($finfo = mysqli_fetch_field($query)) {
$name=$finfo->name;
array_push($colnames, $name);
echo "<th>".$name."</th>";
}
mysqli_free_result($query);
echo '</tr></thead><tbody>';
$count = 0;
echo $colnames[$count]; // this test prints the correct column name but it ends up being printed OUTSIDE the table for some reason
while ($row = mysqli_fetch_array($query, MYSQLI_BOTH)){
echo '<td>'.$row[$colnames[$count]].'</td>';
$count++;
}
echo "</tbody></table>";
}
The last while loop is suppose to echo out each field value but it isn't executing <tbody> is left blank.
You called mysqli_free_result($query) too early. So by the time you called mysqli_fetch_array, the sql result was already gone. Move mysqli_free_result after the last loop.
I'm not sure whether it's a typo or that the following is where the problem lies, but you're missing opening and closing <tr> tags around the column names after <tbody> and before </tbody>. This may help explain why stuff is being printed apparently "outside" the table.

How to grab the id of the search result came from

What you are seeing is my code that displays images as a search result. I have an anchor down there so when you click on the picture it sends you to a TEST page.
I want to have a page set up that will display the rest of the row entries that are associated with that picture:
(Picture) Player: Steve Sax
Card Type: Donruss
Year: 1989
Value: $2.00
How do I grab the "id" in the row of the search result and then echo it in a table that shows up on the TEST page?
<?php
$servername = "*********";
$username = "*********";
$password = "*********";
$dbname = "*********";
$username1=$_SESSION['activeusername'];
$userid = $_SESSION['activeid'];
$userid = $_SESSION['activeid'];
$itemid = $_SESSION['activeid'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM useritems JOIN (users, iteminfo) on (users.id=useritems.UserID AND iteminfo.ID=useritems.ItemID) AND userid='2'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<a href='test1.php'><div id='frame'>
<div id='splash-image' style='background: url(".$row['imagename']."); background-size:cover;'></div>
<div id='text'>
<table >
<tr></tr>
</table>
</div>
</div>";
}
} else {
echo "You Have No Items In Your Closet!!!";
}
mysqli_close($conn);
?>
Pass the id with get as:
echo "<a href='test1.php?id=". $row['id']."'>
And get it on the landing page as:
$id=$_GET['id'];
echo $id;
Assuming the id you want is the item's id, you would echo out
$row['ItemID']
If you wanted to include this ID into your href as a GET parameter you could do something like:
echo "<a href='test1.php?ItemID=" . $row['ItemID'] ."'>...</a>";
Then, in your test1.php, you can retrieve the Item ID for use in your query (after sanitizing it!) by accessing the $_GET global.
$ItemID = $_GET['ItemID'];
If you just wanted the result set row number (not tied to user id or item id), you could echo out something like:
$counter++
or take a look at MySQL - Get row number on select

Echo statement in PHP not executing in a specific manner

I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.

MySQL retrieval from database not retrieving multiple rows

I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php

Display checked checkbox record from database

I have looked through similar problems and solution but somehow only half way help me with my problem. I'm trying to make a form to checked more than one record from MySQL database and display the checked record to another page. Somehow I managed to do the page with check boxes but I don't know how to display the record checked. It can only display the first row of the record or all the records regardless which box are checked.
This is checkbox page
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
{
$rows[] = $row['IllNo'];
}
foreach($rows as $value);
echo "";
echo " ";
echo $row['IllNo'];
echo "";
}
echo "";
?>
This is display record checked
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$rows[]=$row['IllNo'];
foreach($rows as $value);
if ($rows= 'checked') {
echo "";
echo $value;
}
Any help are welcome. Thank you.
There's actually a lot of problems with that script including syntax errors, calling the wrong variable name, form not opening where it should, invoking PHP after you already have, etc...
To get a good answer to you, you should share what make $row['IllNo'] should equal to indicate if it should be checked or not.
I reformatted it a bit and this may give you a good start.
<form NAME ="form1" METHOD ="POST" ACTION ="dari.php">
<table>
<?php
$columns = count($fieldarray);
//run the query
$result = mysql_query("SELECT * FROM request_item ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error()) ;
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
echo "<tr><td>";
echo "<Input type = 'Checkbox' Name ='ch1' value ='ch1'";
// check checked if it is. this will be checked if $row['IllNo'] has a value
// if there were a condition to make it checked, you would put the condition
// before the ?
echo $row['IllNo'] ? ' checked' : '';
echo ' />';
echo $row['IllNo'];
echo "</td></tr>";
}
?>
</table>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Choose your books">
</FORM>

Categories