I am creating a form in php with mysql.
When ever a user enter new data then that data automatically saved into database and also displays browser when i want. This form is for displaying mysql data in a browser.
All is working well. but what my problem is when a user submit data then that data displaying last one. but i need to display that details first in a browser.
<?PHP
$connection=Mysql_connect('xxxresource.com','xxx','xxxx');
if(!$connection)
{
echo 'connection is invalid';
}
else
{
Mysql_select_db('tions',$connection);
}
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
//this part goes after the checking of the $_GET var
$fetch = mysql_query("SELECT * FROM customer_details LIMIT $startrow, 10")or
die(mysql_error());
$num=Mysql_num_rows($fetch);
if($num>0)
{
echo "<table margin=auto width=999px border=1>";
echo "<tr><td><b>ID</b></td><td><b>Name</b></td><td><b>Telephone</b></td><td> <b>E-mail</b></td><td><b>Couttry Applying for</b></td><td><b>Visa-Category</b> </td><td><b>Other Category</b></td><td><b>Passport No</b></td><td> <b>Remarks</b></td></tr>";
for($i=0;$i<$num;$i++)
{
$row=mysql_fetch_row($fetch);
echo "<tr>";
echo"<td>$row[0]</td>";
echo"<td>$row[1]</td>";
echo"<td>$row[2]</td>";
echo"<td>$row[3]</td>";
echo"<td>$row[4]</td>";
echo"<td>$row[5]</td>";
echo"<td>$row[6]</td>";
echo"<td>$row[7]</td>";
echo"<td>$row[8]</td>";
echo"</tr>";
}//for
echo"</table>";
}
//now this is the link..
echo '<img align=left height=50px width=50px src="next.png"/>';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo '<img align=right height=50px width=50px src="previous.png"/>';
?>
My Problem is When a user submit data into mysql database then display that details first in a browser.
Thanks.
You should use ORDER BY clause in your SQL.
SELECT * FROM customer_details ORDER BY ? LIMIT $startrow, 10
Change ? to whichever column you want to sort by.
http://dev.mysql.com/doc/refman/5.0/en/select.html
Related
The title is not most suitable, but this is the best I could think of. Feel free to suggest EDIT.
Summary:
I have come from Android development where I have used RecyclerView to show a grid of various items from the database. There I could use the onClickListener()and Position to get which RecyclerView item (first,second,third..) is clicked by user and can proceed with actions.
Set up:
I am new to web development and by far I have managed to create an HTML table and I am firing appropriate query to get items from the database. I am then showing these data from database in each table cell. The data consists of image link (from a folder in same directory) and other text data about that image. My table looks something like this. Click here
Problem:
I want to add an options like Accept in each cell of the table such that when user clicks on that, a query fires to set the Boolean isAccepted for that item in DB as true. I can manage the query part but I am facing problem how to set this up in my php script.
What do I ecpect?
That's absolutely OK if I dont get the ready made code. I want to be guided as what technology to be used and if possible a link to the guiding tutorial. I hope it can be done usng PHP and HTML only.
My php script:
<table id="customers">
<?php
$MAX_COLS = 5;
$query = "select * FROM `complaints`";
$result = mysqli_query($conn,$query);
$i = 0;
while($row = mysqli_fetch_row($result)){
if($i % $MAX_COLS == 0){
echo "<tr>";
}
echo "<td>";
echo "<img src='SCB2/Images/temp2.jpg' alt='Sample image' style='width:200px;height:200px;' >";
echo "<br>"."Image ID: ".$row[0];
echo "<br>"."Latitude: ".$row[2];
echo "<br>"."Longitude: ".$row[3];
echo "<br>"."Zip: ".$row[4];
echo "<br>"."Done by: ".$row[8];
echo "<td>";
$i++;
if($i % $MAX_COLS == 0){
echo "</tr>";
}
}
?>
</table>
You can add the link to the HTML that is outputted:
echo "<td>";
// ...
echo "<br><a href='/some/path/to/accept.php?imageid={$row[0]}'>Accept</a>";
echo "<td>";
And then in the accept file you can deal with it:
// /some/path/to/accept.php
// Get the image id from the query string
$imageid = filter_input(INPUT_GET, 'imageid', FILTER_VALIDATE_INT);
try {
// Create a database connection
$db = new PDO(
'mysql:dbname=databaseName;host=localhost',
'username', 'pa55w0rd',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
// Create a prepared statement and bind the image id to it
$stmt = $db->prepare('UPDATE complaints SET isAccepted = 1 WHERE Id = :id');
$stmt->bindValue(':id', $imageid, PDO::PARAM_INT);
// Execute the statement
if ($stmt->execute()) {
die('SUCCESS!');
} else {
die($stmt->error);
}
}
catch (\PDOException $e) {
die('PDO Exception: ' . $e->getMessage());
}
You should obviously do some checks that the user is allowed to accept the image.
I'm using this while statement to show all contents of database...
$sql = mysql_query("SELECT id,question,date,user,numberofcomments,body,locked FROM questions ORDER BY id DESC");
while($row=mysql_fetch_assoc($sql)) {
echo '<div class="comment">';
echo '<div class="leftpart">';
echo "<div class='date'><img src='../assets/icons/Time-info.png'> ".ago($row['date']);
echo "</div><br><img src='../assets/icons/User-Info.png'> ".$row['user'];
echo "<br><img src='../assets/icons/Comments.png'> ".$row[numberofcomments];
echo '</div>';
echo '<div class="rightpart-topic">';
if($row['locked']==1) { echo '<img src="../assets/icons/Lock.png" /> ';
}
echo ''.$row['question'].'';
echo '<br>'.substr($row['body'],0,70).'...';
echo '</div>';
echo '</div>';
}
I want to show only 10 rows then have links to show the rest (as in page 1,2,3,4, last type thing). How would I go about doing that? It would help if you could also explain your code as it would be greatly appreciated. It helps my learning process.
Thanks!
You need to do a LIMIT in your query using some sort of passed $_GET variable.
$start=0;
$limit = 10;
$page = (isset($_GET['page']) ? : 0));
$start = $page * $limit;
$sql = mysql_query("SELECT id,question,date,user,numberofcomments,body,locked FROM questions ORDER BY id DESC LIMIT {$start},{$limit}");
Should be pretty self explanatory.
If there is not page variable set then you are viewing page 0, or the first 10 results of your database query. If page = 1 then you are going to be viewing $page (value=1) * $limit (10) = $start (now value of 10), which will give you results 10-20 or page 1. etc.
So provide your user a button which can link them to a hard paginated link, or do it ajax.
Each url will need to be like so:
http://wwww.yoursite.com/somepage.php?page=1
Efficiency aside, you could simply set a counter and check if it value Is greater than 10 during the loop. If so, add a 'hidden' class to the parent div. That class would use display:none;
ok i got this page working well but what would do i have to do to display data from a certain letter?
here is the code i got at present
<html>
<head>
<title>MySQLi Read Records</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = "select * from contacts";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results > 0){ //it means there's already a database record
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Username</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
echo "<td>";
//just preparing the edit link to edit the record
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
//just preparing the delete link to delete the record
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
</body>
</html>
i am wanting to place multiple entries like the following to dislay under the right letter
<h1>A</h1>
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
<h1>b</h1>
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
ECT ECT
what i am trying to acchieve is to dispaly all the surnames that begin with a then b
i have found this bit of code on this page http://www.sitepoint.com/forums/showthread.php?303895-Display-Data-Beginning-with-a-Particular-Letter
but how would i make this work for me?
i am novice (extremly) so any help be fantastic i tried to read tutorials i find it better with hands on :)
Updated ***************************
this is working great but now it only lists one line this is my code
<html>
<head>
<title>MySQLi Read Records</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = " SELECT name,
surname,
mobile,
UPPER (LEFT(surname, 1)) AS letter
FROM contacts
ORDER BY surname";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results > 0){ //it means there's already a database record
echo "<table border='1'>";//start table
//creating our table heading
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<h1>', $row['letter'], '</h1>';
$lastLetter = $row['letter'];
echo "{$surname}";
}
}
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
</body>
</html>
Since you are learning, I will give you the idea of how you can archive what you want and the functions you can use.
As you have mentioned you want all records displayed on the same page with their own alphabet letter as the header.
There is a few ways of doing what you want, the most common is to return the data ORDERed BY the field you want on the order you want, in this case ASC.
This will list all your records in alphabetical order.
From there you can use the function LEFT to extract the first letter as another field.
Now here is where you will use some PHP, from the above you already have your records ordered and the first letter for each record.
You can use something like this inside your while:
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<h1>', $row['letter'], '</h1>';
$lastLetter = $row['letter'];
}
Basically the above will check if $lastLetter has been set/defined which is not for the first record so it will enter the if, print your first header and set $lastLetter to the first letter.
After the first record it will be matching the $lastLetter against the $row['letter'] and once they are not equal, it prints the header again and update the $lastLetter with $row['letter'] which is the current letter.
Your MySQL query would look like this:
SELECT *,
LEFT(firstname, 1) AS letter
FROM contacts
ORDER BY firstname
However it is always better to define all fields you need instead of catching all the fields in case you have more fields on the table in question:
SELECT firstname,
surname,
mobile,
LEFT(firstname, 1) AS letter
FROM contacts
ORDER BY firstname
NOTE in case your names are not normalize you can use the UPPER function to make the letter uppercase like this:
SELECT firstname,
surname,
mobile,
UPPER(LEFT(firstname, 1)) AS letter
FROM contacts
ORDER BY firstname
See more about the UPPER function here
I suggest you do the following steps.
Update your mysql query statement
$query = "select * from contacts order by name_field";
Name_field or whatever is the column name so that you get the result set sorted in dictionary order.
Keep $previous to keep track of what letter you added last time.
Use this function (refer startsWith() and endsWith() functions in PHP) at each row to find whether the name value starts with a different letter from $previous. If there is a change then update $previous and include "" tags with the letter as you desire.
function startsWith($haystack, $needle)
{
return $needle === "" || strpos($haystack, $needle) === 0;
}
First of all you should change your SQL query to:
SELECT * FROM contacts ORDER BY name ASC
this will sort all of the contacts from A to Z. Now, to able to determine an initial alphabet of a contact name use substr function...
$initial_letter = strtoupper(substr($name, 0, 1));
I'm creating a web-based booking system where a user can add bookings into a database, and the details stored in the database are (among others) "DateBooked, StartTime, EndTime, Room".
Here's the bit that pulls the relevant info for the day the user has clicked on from the database:
$query="SELECT * FROM bookings WHERE DateBooked = '{$year}-{$selectedmonth}-{$selectedday}'";
$result = mysql_query($query);
$todayarray = mysql_fetch_array($result);
And the PHP:
$roomcount = 4;
$room = 1;
while ($room <= $roomcount)
{
echo "\n<div class=\"roomtimes\">";
echo "\n<table border=1>";
echo "\n<tr><th class=\"titlecell\">Room $room</th></tr>";
$cellnum = 10;
while ( $cellnum < 23 )
{
echo "\n<tr>";
echo "\n<td class=\"linkcell";
if ($selectedtime==$cellnum)
{
echo " selectedcell";
}
echo "\">";
echo "$cellnum:00</td>";
echo "\n</tr>";
$cellnum++;
}
$room++;
echo "\n</table>";
echo "\n</div>";
}
So my question is, how can I add a bit of text saying "BOOKED" inside each table cell if a entry exists for that room and the number in that cell is in between the start time and end time of that booking?
I'm new to this site so let me know if I've done something wrong or you need more information, thanks!
You need to divide the cell content html and insert your "BOOKED" text there. And I suggest you use mysql_fetch_assoc so you get and associative array and it's easier to get the fields. If I'm understanding your code correctly you might be able to use something like this. This example is a replacement for the row that has the link output in it. I've used mysq_fetch_assoc here to get the StartTime and EndTime fields from the database. You might need to change the fields a bit depending in what data format they are.
echo "$cellnum:00";
if ($todayarray['StartTime'] <= $cellnum && $todayarray['EndTime'] >= $cellnum && $todayarray['Room'] == $room) echo 'BOOKED';
echo "</td>";
This is my php code for displaying the data from the database. I am trying to display the random data from table.
<?php
include('connection.php');
$query="SELECT * FROM `banner_ad` ORDER BY RAND() LIMIT 4";
if($query_run=mysql_query($query))
{
$i=4;
$rows=mysql_fetch_array($query_run);
while($rows)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
}
} else {
echo'<font color="red"> Query does not run. </font>';
}
?>
But the problem with this code is:
It is displaying nothing. But whenever I am trying to make a little modification in the above code like:
<?php
include('connection.php');
$query="SELECT * FROM `banner_ad` ORDER BY RAND() LIMIT 4";
if($query_run=mysql_query($query))
{
$i=4;
$rows=mysql_fetch_array($query_run);
while($rows && $i<4)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
$i=$i-1;
}
} else {
echo'<font color="red"> Query does not run. </font>';
}
?>
It is displaying the same single output 4 times. But It has to display the four different output. So, Please tell me where is the bug ... And how am i suppose to display four different random output.
Any help will be appreciated
Thanks in advance
Your first Query is fine, but the while is wrong:
Just look at what you did here:
$rows=mysql_fetch_array($query_run);
while($rows)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
}
this will end in an "infinite Loop" cause $rows will always be set.
What you need is:
while($rows=mysql_fetch_array($query_run))
this will cause myslq_fetch_array to return a new line everytime the while condition is checked. And if all 4 rows are returned, $rows will be false and the loop is stoped.
And to be complete:
In your second Example you are exactly iterating 4 times over the SAME row, you just fetched one time by calling myslq_fetch_array.
A possible solution to that will be to fetch the row again INSIDE the while-loop:
$i=4;
while ($i>0){
$rows = mysql_fetch_array(...);
$i--;
}
However you should prefer the first solution, because then you dont need to take care that the result count matches your iterator variable.
sidenode: Call it $row without the 's', because you always just getting ONE row back.
Try constructing while loop like so
while(($rows=mysql_fetch_array($query_run)) !== false)
Using ORDER BY RAND() is not the best practice because the random value must be generated for every single row. Better way would be to randomly generate primary keys (e.g. ID) in PHP and then select according to them.
$random_id = rand(1,4);
$query="SELECT * FROM `banner_ad` WHERE id = $random_id";
Will select exactly one random row. Similar whould be selecting multiple rows using IN statement.
More info you can find here.
$query_run=mysql_query($query);
if(!$query_run)
{
echo'<span style="color:red">Query did not run.</span>';//font tag is ancient
}
else
{
if(mysql_num_rows($query_run) > 0)
{
while($row = mysql_fetch_assoc($query_run))
{
echo $rows['banner_no'];
echo $rows['banner_name'];
// more...
}
}
}