I am having problem trying to get a web url working within php, I am basically getting a list of content displayed, the list content becomes a links to a result webpage (detail.php). I want to display the result webpage with more detailed info. on the same webpage with a back button to original list.
=====
my list webpage code
=====
$c = 0; //Variable to keep count of categories
$servicetype = '$brand'; //variable declaration last displayed servicetype.
$strSQL = "SELECT * FROM <tablename> ORDER BY serviceType, serviceName ASC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
//If the servicetype name has changed, display it and update the tracking variable
if ($servicetype != $row['serviceType']){
$servicetype = $row['serviceType'];
//If this isn't the first category, end the previous list.
if ($c>0) echo "</ul>";
echo '<h3>'.$row['serviceType'].'</h3><ul>'; // subheading & related content.
$c++;
}
$strName = $row['serviceName'];
$strLink = "<a href = 'detail.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
// Close the database connection
mysql_close();
?>
====
my detail.php code below
=====
$strSQL = "SELECT * FROM gu_service_cat WHERE id = " . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the detail data of the ID
echo '<h3>ID:</h3>' . $row['ID'] . ' ' . $row['guUrl'] . "</dd>";
echo "<dt>availability:</dt><dd>" . $row["availability"] . "</dd>";
}
//echo '<h3>'.$row['serviceType'].'</h3><ul>';
// Close the database connection
mysql_close();
?>
</dl>
<p>
Return to the list
I do see you incorectly using variable variables.
This is incorrect:
$servicetype = '$brand';
if ($servicetype != $row['serviceType'])
What you need to do is assign the variable $servicetype a string, in this case 'brand' and use that in the if statement:
$servicetype = 'brand';
if ($$servicetype != $row['serviceType'])
Notice the double dollar sign. Read more about Variable Variables.
Related
I want to pass a unique session for each link that user clicks on, something like this:-
$sql = "select * from modulestb where teacherid=?";
$st = $pdo->prepare($sql);
$st->execute(array($_SESSION['logid']));
foreach ($st as $row) {
$_SESSION['stage'] = $row['stage'];
$_SESSION['mid'] = $row['mid'];
echo "<a style='color:white;' href=report.php?>" . $row['name'] . " (Stage :" . $row['stage'] . "</a>";
}
As an example:
I haven't tested this code but I hope you understand the concept :-)
<?php
//Always use this preferbly at the start of the script
//when dealing with sessions in PHP
session_start();
//If data isset and contains anything
if (!empty($_GET['data'])) {
$data = unserialize($data); //Restore to the array
$id = $data['mid'];
//Set the actual session based on what user has clicked on
//If user has clicked on mid 1 , this will store $_SESSION['module1'] = value of stage
//If user has clicked on mid 2 , this will store $_SESSION['module2'] = value of stage
//etc
$_SESSION['module'.$id] = $data['stage'];
}
$sql = "select * from modulestb where teacherid=?";
$st = $pdo->prepare($sql);
$st->execute(array($_SESSION['logid']));
foreach ($st as $row) {
//Serialize the data you want to save into your session
//(Make the array a string that represents the array)
$data = serialize(array('stage'=>$row['stage'],
'mid' => $row['mid']));
echo "<a style='color:white;' href=report.php?data=$data>" . $row['name'] . " (Stage :" .
$row['stage'] . "</a>";
}
I'm starting to build a very simple product display system, mainly to build my own skills, but also for use on my website for work.
List.php
<html>
<head>
<title>Retrieve data from the database</title>
<?php
$username='';
$password='';
$database='';
?>
</head>
<body>
<ul>
<?php
// Connect to database server
mysql_connect(localhost,$username,$password);
// Select database
#mysql_select_db($database) or die( 'Unable to select database');
// SQL query
$sql = "SELECT * FROM products WHERE category = 30";
// Execute the query (the recordset $rs contains the result)
$result = mysql_query($sql);
// Loop the recordset $rs
while($row = mysql_fetch_array($result)) {
// Name of the person
$strName = $row['make'];
// Create a link to person.php with the id-value in the URL
$strLink = "<a href = 'product.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
// Close the database connection
mysql_close();
?>
</ul>
</body>
</html>
Product.php
<html>
<head>
<title>Retrieve data from database</title>
</head>
<body>
<?php
$username="";
$password="";
$database="";
// Connect to database server
mysql_connect(localhost,$username,$password);
// Select database
#mysql_select_db($database) or die( "Unable to select database");
// Get data from the database depending on the value of the id in the URL
$sql = mysql_query('SELECT * FROM products WHERE ID=' . $_GET["ID"]);
$result = mysql_query($sql);
if(!$result)
die(mysql_error());
// Loop the recordset
while($row = mysql_fetch_array($result)) {
// Write the data of the product
echo $row['category'];
echo "<p>";
echo $row["make"];
echo "<p>";
echo $row["description"];
echo "<p>";
echo $row["picture"];
}
// Close the database connection
mysql_close();
?>
<p>Return to the list</p>
</body>
</html>
Can be seen messing up HERE
If someone can help get this working for me I'd be very grateful!
Try this way, but not fully sure about this stubborn issue. You can try by changing the case of all keys of the $_GET array to lowercase using the array_change_key_case()
$get = array_change_key_case($_GET);
$id = $get['id'];
$sql = mysql_query('SELECT * FROM products WHERE ID=' . $id);
NB: Make first sure SELECT * FROM products WHERE ID=your_row_id return results or not?
I turned out that the link that the page 'list.php' was generating was incorrectly formatted.
Changed this:
$strLink = "<a href = 'product.php?id = " . $row['ID'] . "'>" . $strName . "</a>";
To
$strLink = "<a href = 'product.php?id=".$row['ID']."'>" . $strName . "</a>";
And it's now working exactly as it should!
I have a bunch of items I list on a page and each of these items have an id associated with them on there link.
For instance, when you hover over the items you get a url of items.php?id=5.
I have my while loop which produces all of the items on this page including the links, how do I carryover that ID into my other code?
Here is my code that brings up all the items.
while ($results = mysqli_fetch_assoc($query)) {
echo
"<li>
<img style='width: 200px; height: 200px' src='images/inventory/" . $results['Image'] . "'/>" .
"<div class='infoContainer'>" .
"<a class='productLink' href='selectItems.php?status=active&id=" . $results['ID'] . "'>" . $results['ProductName'] . "</a>" .
"<br />" .
"<i>Currently Available </i>" .
"<i class='quantity'>" . $results['Quantity'] . "</i>" .
"</div>" .
"</li>";
}
Now I simply want to put each items attributes into a dialog box. How do I carryover an id from above to get the right data back?
<div id="dialog" title="A title">
<?php
$sql = "SELECT * FROM `my_table` WHERE `id` = ";
$query = mysqli_query($sql) or die(mysqli_error());
var_dump($sql);
$results = mysqli_fetch_assoc($query);
var_dump($results);
?>
</div>
You should call a javascript function and send id in it..
donot forget to include the jquery files..
this method loads the data using AJAX..
<script>
function getData(idtosend){
$.post('getdata.php', id: idtosend, function (response){
$("#dialog").html(response);
});
}
</script>
Here is the code of getdata.php file:
<?php
//Connect mysql here
$id = mysql_real_escape_string($_POST['id']);
$sql = "SELECT * FROM `my_table` WHERE `id` = $id";
$query = mysqli_query($sql) or die(mysqli_error());
var_dump($sql);
$results = mysqli_fetch_assoc($query);
var_dump($results);
?>
in PHP you cat use ob_start() - this is output buffer for echo operations.
after save result in variable or array and put it into needful block on page
I need help displaying data from mysql to a webpage, I am coding in php.
My database consists of products which are cars(same type e.g Chevy), right now I have 2 rows (I can add more if I want to), each cars contains the image path, and description.
I can show one row (car) but I am unable to show all rows. I know I have to go through a loop to get all the data from the cars database but I am not sure how to implement it.
This is what I have so far. Assuming I already connected to my database
note: the image path I would like to show the picture in my website.
This is how i would like it to display in my webpage:
$query = "SELECT * FROM cars where cars.carType = 'Chevy' AND \
cars.active = 1";
$numberOfFieds = mysqli_num_fields($result);
$numberOfRows = mysqli_num_rows($result);
/* Gets the contents */
$row = mysqli_fetch_row($result);
$rows = mysqli_fetch_assoc($result);
$fieldcarssontable = array_keys($row);
echo "<table>";
while($row = mysqli_fetch_assoc($result)){
echo "<th>" . $fieldcarssontable[imgPath] . "</th>";
echo "<th>" . $fieldcarssontable[description] . "</th>";
}
echo "</tr>";
echo "</table>";
Just add a while loop. mysqli_fetch_assoc returns a row and moves the internal pointer to the next row until all rows are fetched, then it returns false and the while loop will stop
Pseudo syntax to understand while
while ( this is true ) {
execute this
}
So on your case you can say
while ( $row = mysqli_fetch_assoc( $result ) ) {
// process/output $row
}
mysqli_fetch_assoc and mysqli_fetch_row literally do the same, assoc gives you the array with your result field names as index so this is simpler to access ( $row['name'] rather than $row[0] when using fetch_row )
Have fun! :)
EDIT
// connect to your database server
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
// an error occured
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
// build your query
$query = "SELECT
* # select actual fields instead of *
FROM
cars
WHERE
cars.carType = 'Chevy'
AND
cars.active = 1";
// execute query
$result = mysqli_query($link, $query );
if ( !$result ) {
die( 'no result' );
}
// number of fields
$numberOfFields = mysqli_num_fields($result);
// the field names
$fieldNames = mysqli_fetch_fields($result);
// number of result rows
$numberOfRows = mysqli_num_rows($result);
// watch the content of fieldName and compare it with the table header in the output
print_r( $fieldName );
echo "<table>\n";
// table header, not neccessary to put this into a loop if the query isn't dynamic
// so you actually know your field names - you can echo the header without any variable.
// for the sake of learning about loops I added this
foreach( $fieldNames as $index => $fieldName ) {
echo "\t<th>field #" $index . ", name:" . $fieldName . "</th>\n";
}
// now it's time to walk through your result rows, since we only need to check for "true" a while loop does best
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo "\t<tr><td>" . $row['imgPath'] . "</td><td>" . $row['description'] . "</td></tr>\n";
}
echo "</table>\n";
// remove the result from memory
mysqli_free_result( $result );
mysqli_close( $link );
You misspelled $numberOfFields in your loop, which means you're using a different variable for your loop control. Your loop won't work.
I recommend turning on the error reporting so PHP can catch this stuff for you.
Use this... just while loop
<?php
// Array
while($result = mysql_fetch_assoc($result)) {
//show you fields
echo $result["FieldName"];
}
?>
Or use this proper
<?php
// Edit it as per your query
$query = "SELECT * FROM cars";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while($row = $result->fetch_assoc()) {
//show you fields
echo $row["Name"];
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
Okay, been thrashing around with this for longer than I care to think about!
I am trying to drag event data from mysql so that it displays the Event Name once and several products under that Event Name
For Example:
Event Name
product 1
product 2
product 3
What is currently happening is that the Event Name is displayed above each product, like this
Event Name
product 1
Event Name
product 2
Event Name
product 3
The PHP Code is:
<?php
// Get the search variable from URL
$var = #$_GET['q'] ;
$trimmed = trim($var); //trim whitespace from the stored variable
// rows to return
$limit=10;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("xxxxxxxx","xxxxxxxx","xxxxx"); //(host, username, password)
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("event_db") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "select * from event where event_name like \"%$trimmed%\"
order by event_name"; // EDIT HERE and specify your table and field names for the SQL query
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
// google
echo "<p><a href=\"http://www.google.com/search?q="
. $trimmed . "\" target=\"_blank\" title=\"Look up
" . $trimmed . " on Google\">Click here</a> to try the
search on google</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "Results<br /><br />";
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["event_name"] . "<br />";
$title2 = $row["location"] . " - " . $row["style_name"] . "<br />";
echo "<b>$title</b>";
echo "$count $title2";
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
// next we need to do the links to other results
if ($s>=1) { // bypass PREV link if s is 0
$prevs=($s-$limit);
print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a>  ";
}
// calculate number of pages needing links
$pages=intval($numrows/$limit);
// $pages now contains int of pages needed unless there is a remainder from division
if ($numrows%$limit) {
// has remainder so add one page
$pages++;
}
// check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
// not last page so give NEXT link
$news=$s+$limit;
echo " Next 10 >>";
}
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
Any thoughts would be greatly received.
simply use group_concat -> group_concat query performance
details -> http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
newbie including myself, please try google before posting the question
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
if($row["event_name"] != $lasteventname){
$title = $row["event_name"] . "<br />";
$lasteventname = $row["event_name"];
echo "<b>$title</b>";
}
$title2 = $row["location"] . " - " . $row["style_name"] . "<br />";
echo "$count $title2";
}