Retrieve data from a dynamically created html table - php

Here is my problem:
I have a dynamically created html table that I got with mysql_fetch_array
I would actually like to retrieve the first cell of a line when the user clicks on the last cell of this very same line (circle_plus_grey.png in the code).
If possible I would like to retrieve the first cell content (song_name) by using PHP, my final goal being to send an email including with the content of the first cell.
Thank you so much for your help, here is my code :
<?php
$query = $_GET['mood'];
// gets value sent over search form
$min_length = 1;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM song_main
WHERE (`song_name` LIKE '%".$query."%') OR (`song_artist` LIKE '%".$query."%') OR (`song_album` LIKE '%".$query."%')" ) or die(mysql_error());
$num = mysql_num_rows($raw_results);
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
echo '<table id="hor-minimalist-a" summary="songs table">
<thead>
<tr>
</tr>
</thead>
<tbody>';
echo'<td width="270px">'. ucfirst($results['song_name']).'</td>';
echo'<td width="200px">'. ucfirst($results['song_artist']).'</td>';
echo'<td width="270px">'. ucfirst($results['song_album']).'</td>';
echo '<td>';
echo '<a href="linkto.php"/><img src="images/circle_plus_grey.png">';
echo '<a href="#"/><img src="images/play_overlay.png">';
echo '</td>';
}
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
echo'</tr>
</tbody>
</table>';
?>

You can send the first column content as a GET parameter to the other script.
echo '<a href="linkto.php?data='.ucfirst($results['song_name']).'"><img src="images/circle_plus_grey.png">';

Related

PHP How do you separate your results to echo in two divs of the one page?

I know how to produce results one after another but how do you separate them? So in my sql I'm selecting * from table and limiting it to 4
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{$rows['id']=$row;};
$price = $row['price'];
I dont seem to get any result, any suggestions, sorry guys beginner
...<?php echo $id ?></font></span>
<h4><?php echo $price ?></h4></div>
<div class="planFeatures"><ul>
<li><h1><?php echo $id=2 ?></h1></li>//how do I echo the next id?
<li><?php echo $price2 ?></li> //also the next price which id now is also 2
//and so on......
How do I display the next increments results in a different area of the same page, within another div?
I do get results if I sql and re-select all over again (and say id=2) but I'm sure there is a better way of doing it because I've already got my 4 results with my limit.
It seems you are not saving the results from the query result properly. Each iteration of the loop overwrites the same bucket in the $rows array. Instead, you need to add elements to the $rows array; this will produce an indexed array. Then you can iterate over it and generate the HTML content.
<?php
// Perform query.
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
// Fetch results
while (true) {
$row = $result->fetch_assoc();
if (!$row) {
break;
}
$rows[] = $row;
}
// Generate HTML content using $rows array.
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row):?>
<tr>
<td>ID: <?php print $row['id'];?></td>
<td>Price: <?php print $row['price'];?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I took some liberty in the above example and generated a simple HTML table. Of course you can modify this to generate whatever you want.
I hope I've interpreted your question accurately, apologies if not!

create table with loop in Php

What I want is show the total clicks per Category id of the items only for 20 items order by the highest total clicks per day.
Now I am using hard code and the result have to looks like this
So, if the item id and total clicks already fill up the
20columns (for item id and total clicks) + 2 for the tittle so means
22columns
It has to move to next row.
Because I am referring to my db, so I am using loop to create the table, and when I doing that way, I am getting this result....
The result will keep showing until the end in the left side. Thats very hard to read for report purposes. I wanted the result looks like the first figure that I've uploaded.
Here is what I am doing now:
include "Con.php";
//get the value from Get Method
$CatidValue = $_GET['CatIds'];
//(The date format would looks like yyyy-mm-dd)
$DateFrom = $_GET['DateFrom'];
$DateTo = $_GET['DateTo'];
//select the CatID
$SqlGet= "Select CatId from try where CatId = $CatidValue";
$_SqlGet = mysqli_query($connection,$SqlGet);
$TakeResultGet = mysqli_fetch_array($_SqlGet);
$CatIdTittle = $TakeResultGet ['CatId'];
echo"
For Category Id : $CatIdTittle
<br>
";
//For Loop purpose and break the value
$explodeValueFrom = explode("-",$DateFrom);
$explodeValueTo = explode("-",$DateTo);
$DateValueFrom = $explodeValueFrom[0].$explodeValueFrom[1].$explodeValueFrom[2];
$DateValueTo = $explodeValueTo[0].$explodeValueTo[1].$explodeValueTo[2];
//Loop through the date
for($Loop=$DateValueFrom; $Loop <= $DateValueTo; $Loop++){
$YearLoop= substr($Loop, 0,4);
$MonthLoop =substr($Loop, 4,2);
$DayLoop = substr($Loop, 6,2);
$DateTittleValue = $YearLoop."-".$MonthLoop."-".$DayLoop;
$trValue = "<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<table class='tg'>
<tr>
$trValue
</tr>
";
echo"
<table class='tg'>
<tr>
<td class='tg-yw4l'>Items Id</td>
<td class='tg-yw4l'>Total Clicks</td>
</tr>
";
//to get the item id and total clicks
$SqlSelect = "select `Item Id`,`Total Clicks`,Day from try where CatId = $CatidValue and Day = '$DateTittleValue' ORDER BY `try`.`Total Clicks` DESC limit 20";
$_SqlSelect = mysqli_query($connection,$SqlSelect);
foreach ($_SqlSelect as $ResultSelect) {
$Day = $ResultSelect['Day'];
$ItemId = $ResultSelect['Item Id'];
$TotalClicks = $ResultSelect['Total Clicks'];
echo"
<tr>
<td class='tg-yw4l'>$ItemId</td>
<td class='tg-yw4l'>$TotalClicks</td>
</tr>
";
}
}
?>
you need to add td dynamically within a table for each day report ( data should be grouped by date).
You just need to float each table with the float:left css property and some percentage based on the number of tables you want on the same row. In this case, 33% will do. Take a look at this codepen: http://codepen.io/anon/pen/EgXqPk
The magic happens on:
.tg {
width: 33%;
float:left;
}
you can try i hope this perfect for you to draw a table using PHP Loop.
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 10; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 10; $col++) {
$p = $col * $row;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>

Display an image from the databse to results page

Is it possible for a user to input let's say 'Red Car' and it will find the image in the database and in php/html and in the search results it will show the image?
My code for "Search"
<?php
$query = $_GET['query'];
$min_length = 3;
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM articles
WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text`
// articles is the name of our table
// '%$query%' is what I'm looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<div class='successmate'><h2></h2></a>
</div><br><br><br>";
echo "<div class='search69'><a href='../pages/{$results['page_name']}'><h2>{$results['title']}</h2></a><p>{$results['text']}</‌​p>";
}
}
else{ // if there is no matching rows do following
echo ("<br><br><div class='search1'><h2>No results</h2></br></br>");
}
}
else{ // if query length is less than minimum
echo ("<br><br><div class='search1'><h2>Minnimum Length Is</h2><h2>".$min_length);
}
?>
The images that I want to be found for keywords:
http://puu.sh/cCHv1/9f58d770f3.jpg
These are the names of the images in the DB:
http://puu.sh/cCHwa/a82d2cc7fe.png
Thanks!
Without testing I'd say you have your search function down, to display the results would be a simple matter simply put the below code where you would want to display the image results (This will only be for displaying the images, but to get it to work with other results is a simple rework)
<?php
while($data = $result->fetch_assoc()){
echo '<img src="'.$data['image_path'].'" alt="" title="" />';
}
?>
And then you can simply wrap the images in what ever container if you wish so, another way to do it could be to store the results into an' array and display it with a foreach loop
<?php
while($data = $result->fetch_assoc()){
$imageArray[] = $data['image_path'];
}
/*Code below you can place where ever you want, no need to place it directly after the
above query execute*/
foreach($imageArray as $imgPATH){
echo '<img src="'.$imgPATH.'" alt="" title="" />';
}
?>
The way i understand the problem, i would do it like this
Edit your database table so you also got "image_name", after image where you contain "ser_pic1.jpg"
SELECT * FROM {your_database} WHERE image_name = "Red car"
And post it like
link here

display data from a certain letter

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));

Display Last entry in first row in a browser

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

Categories