Accessing MySQL field values from mysql_fetch_array - php

I have written a calendar implementation, which is working, but displays only one set of data, I'm trying to make it appear all of the data in my select query:
$events = '';
$query = mysql_query('SELECT event_id, event_type, time, date, location, home_or_away, team_id FROM event WHERE date = "'.$deets.'"');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$events .= '<div id="eventsControl"><button onMouseDown="overlay()">Close</button><br /><br /><b> ' . $deets . '</b><br /><br /></div>';
while($row = mysql_fetch_array($query)){
I know it has to do with something with this, but I don't know exactly what code to imply to get 'event_type', 'time' and etc
$desc = $row['event_id'] ;
$events .= '<div id="eventsBody">' . $desc . '<br /> <hr><br /></div>';
}
}
echo $events;
?>

You can use your columns as keys in the array. So to have time, use $row['time'] and so on.
For showing multiple data, try concatenating
$desc = $row['time'] .$row['event_type']

You mean something like
$time = $row['time']
etc?
I'm not sure I've got your point

not sure what you are trying to do but if you are trying to display all columns, you can use a foreach loop
while($row = mysql_fetch_array($query)){
foreach($row as $key=>$value)
{
echo("<b>$key</b>$value<br/>");
}
}

Related

SQL Select producing slightly different results in phpAdmin vs. phpHTML

I consistently miss the first row result, which is more noticeable when there is only one row result.
I have a problem with my PDO commands. Any suggestions for how to correct please? If I remove the $pod->prepare nothing works. Not sure what to do?
<?php
$sql = "SELECT * FROM Order_Items
JOIN Parts ON Parts.id = Order_Items.part_id
WHERE Order_Items.orders_id = $id
AND qty <> 0
ORDER BY Parts.id";
$q = $pdo->prepare($sql);
$q->execute(array());
$row = $q->fetch(PDO::FETCH_ASSOC); // Roy says this is not needed
while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>';
echo '<td>' . $row['part_num'] . '</td>';
echo '<td>' . $row['part_desc'] . '</td>';
echo '<td>' . $row['qty'] . '</td>';
}
Database::disconnect();
?>
You are duplicating $row = $q->fetch(PDO::FETCH_ASSOC);.When you asing $q to $row, $q->fetch is cleared (with no data) so in the IF sentence you have no rows to fetch in $q.
You have to remove $row = $q->fetch(PDO::FETCH_ASSOC); and just use it in the IF.
Also try to do a fetchAll() to $q.
$result = $query -> fetchAll();
foreach( $result as $row ) {
/*CODE*/
}
You are not getting an SQL error. This has nothing to do with the value of the line_item_id database column.
You are getting a PHP error. The variable $line_item_id is undefined.

Is it possible to wrap looping PHP output in tags?

everyone. I'm having a bit of a PHP conundrum here and I couldn't find a good answer that already existed. You see, I'm working on a project where I have to take a classmate's discography website and revamp it with PHP, to where, instead of having the album covers and tracklists hard-coded in, it would query the database for them. My problem is that I have to keep the general style of his site intact, and I'm having trouble doing that. Basically his styles depend on having the album cover, name, and tracklists in div tags, and the style he's got in place is achieved through both Bootstrap and his own, custom CSS stylesheet.
Before I start to ramble, my question is: is there any way to wrap looping output in HTML tags? I need to get the album cover, album name, and tracklists in a div tag, but only the tracklists loop. Here is the code I have in place to query the database:
<?php
require ('mysqli_connect.php');
// Connect to database server
mysql_connect("localhost", "admin", "instructor") or die(mysql_error());
// Select database
mysql_select_db("phprediscography") or die(mysql_error());
// SQL query
$q = "SELECT DISTINCT albums.albumname, albums.albumID, albums.coverart
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID"; //select UNIQUE results from database
$t = "SELECT trackname FROM tracks WHERE albumID = 1";
$b = "SELECT trackname FROM tracks WHERE albumID = 2";
$n = "SELECT trackname FROM tracks WHERE albumID = 3";
$r = "SELECT trackname FROM tracks WHERE albumID = 4";
$result = mysqli_query($dbcon, $q);
$result1 = mysqli_query($dbcon, $t);
$result2 = mysqli_query($dbcon, $b);
$result3 = mysqli_query($dbcon, $n);
$result4 = mysqli_query($dbcon, $r);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //loop through database to get each album
echo '<img class="img-responsive" src=' . $row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
if ($row['albumID'] == 1) {
foreach($result1 as $row1) { //loop through tracks and output to page
echo '<p>' . $row1['trackname'] . '</p>';
}
}
if ($row['albumID'] == 2) {
foreach($result2 as $row2) { //loop through tracks and output to page
echo '<p>' . $row2['trackname'] . '</p>';
}
}
if ($row['albumID'] == 3) {
foreach($result3 as $row3) { //loop through tracks and output to page
echo '<p>' . $row3['trackname'] . '</p>';
}
}
if ($row['albumID'] == 4) {
foreach($result4 as $row4) { //loop through tracks and output to page
echo '<p>' . $row4['trackname'] . '</p>';
}
}
}
// Close the database connection
mysql_close();
?>
If I need to post anything else, let me know, this is my first-ever question so I'm just kind of feeling it out.
By doing your $t = "SELECT trackname FROM tracks WHERE albumID = #"; and if($row['albumID']==#) you are essentially still hardcoding similar to your friend. Just do 1 query, where you join all the tracks. Then when looping, group by the albumname -
<?php
require('mysqli_connect.php');
// SQL query
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$current_albumID = ""; //create current albumID var to be used below.
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//loop through database to get each album
if($row['albumID'] != $current_albumID){
echo '<img class="img-responsive" src='.$row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
$current_albumID = $row['albumID']; // set current albumID to this albumID
}
echo '<p>' . $row['trackname'] . '</p>';
}
?>
Try something like this instead: Get all the data you're after in your first query, then use php to process that into your output:
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$lastAlbumId = null;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if ($lastAlbumId != $row['albumID']) {
echo '<img class="img-responsive" src="'.htmlentities($row['coverart']).'"><br />';
echo '<h2>'.htmlentities($row['albumname']).'</h2><br />';
}
echo '<p>'.htmlentities($trackname).'</p>';
$lastAlbumId = $row['albumID'];
}
A few things to note:
I added use of htmlentities to escape the user data so malicious people can't type in HTML somewhere and have it appear on your site. This is something you should do almost everywhere you're displaying data from a database in a html site, except for very rare cases where you know what you're doing.
You probably don't need those <br /> tags - <h2> is a block level element so it'll force itself onto it's own line anyway (unless there's some silly CSS rules somewhere).
Also note - the above code is untested - typed straight into browser. There may be some syntax errors - let me know if you see any problem and I'll happily edit the answer. (or you can suggest an edit).

full text ranking [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
how to have ranking based on how many words match user input
How can I have a search engine ranked by amount of words that are typed in and ranked by the amount of types they crop up in the fields title, description, keywords, link.
So the higher results are ordered by having more of the words that the user submitted. Say if the user typed in iPhone, iPhone key word crops up in the link, description and title field, so that would be ranked higher than say Apple which mentions it only in the description and Apple Store which mentions it in the title and the description.
My code is below:
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "Match(title, description, keywords, link) Against ('".implode(' ',$terms)." IN BOOLEAN MODE') ";
}
$secs = microtime();
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
echo '<p class="time">Qlick showed your results in ' . number_format($secs,2) . ' seconds.</p>';
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title1 = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$rank = $row['rank'];
$title = substr($title1,0,60);
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
While I'm sure it is possible to implement this within mysql, a full-text search index like solr/lucene is designed to handle this stuff directly. You might find better resources & help going down that road.
Using php, copy the array returned by the mysql query:
while ($row = mysql_fetch_assoc($query))
{
$rows[] = $row;
}
Then you can loop over $rows and assign a score to
foreach ($rows as $row)
$row['score'] = score_row($row, $terms)
score_row is a helper method that returns a bigger score depending on which columns have which terms and your definition of "importance".
Then sort thw rows by score, then print the results as you were doing.

PHP: using SQL result in a loop without re-executing query

I am trying to add 3 combo boxes which all display the exact same information that comes from my MySQL db. It seems like the code I wrote makes the entire page wait until all 3 combo boxes are populated, before continuing.
<?
$query = "Select * from tblWriters order by surname";
for ($i = 1; $i <= 3; $i++) {
$result = mysql_query($query);
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] . ", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
?>
I would like to optimize this piece of code, so the query will not be executed 3 times, as I believe this is where the page slows down.
If I put
$result = mysql_query($query);
outside of the for loop, the 2nd and 3rd combo box do not populate. I tried looking into resetting the pointer of the result, but I can't seem to figure out how that works.
Also, is there a way I can reuse the while loop, so I don't have to execute it 3 times?
Can someone point me in the right direction?
I'm pretty new to PHP and trying to learn on my own. Any help would be much appreciated. Thanks!
If you move your mysql_query() out of the loop again, you can reset your mysql-result-pointer by using mysql_data_seek() at the beginning or end of your loop.
This will result in:
mysql_query($query);
for($i=1;$i<=3;$i++);
{
mysql_data_seek(0); // reset datapointer
// output querydata
}
I'm obliged however to point out that the mysql-extension is deprecated by now and you should use mysqli or pdo for new projects and code.
Cache the query result in an array, then generate your markup:
$query = "Select * from tblWriters order by surname";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[] = $row;
}
for ($i = 1; $i <= 3; $i++) {
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
foreach ($data as $row) {
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] .
", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}

PHP MYSQL while change field name each time

I have a database to store people's quick links. This is a very basic quick link storage method. The database looks like this:
full_name | 1url | 1name | 2url | 2name | 3url |3 name | 4url |4name | 5url | 5name
^This goes on until 10. I know this is a bad way, but this is for an unprofessional website.
I will want to put the result into an ordered list. But I am unsure how to change the number (1url or 2url) each time?
So currently I have it set up like this in PHP
$result = mysql_query(SELECT * FROM `links` WHERE `full_name`='$loggedin')or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<li><a href="';
echo $row['1url'];
echo '"></a></li>';
}
But I am having no luck with that! I'm very unsure of what I should do. I want it to display another <li> with an <a> and the link plus name of the link for each row found.
Thanks! Please be specific with me, as this is new ground! :D
EDIT:
I have also run into another problem. I have used code from peoples' answers and most of them work. However, If one of the fields is blank (so a user has only 6 quick links) it still shows an <li>. Now I can't see anyway round this issue. :/
SOLUTION:
Here is what works:
while($row = mysql_fetch_array($result)){
for($i = 1; $i < 10; $i++) {
if(!trim($row[$i . 'url'])=='') {
echo '<li><a href="';
echo $row[$i . 'url'];
echo '">';
echo $row[$i . 'name'];
echo '</a></li>';
} //end of didn't trim
}//end for for
}//end of while
$result = mysql_query("SELECT * FROM `links` WHERE `full_name`='$loggedin'")or die (mysql_error());
while($row = mysql_fetch_array($result)){
for($i = 1; $i < 10; $i++)
{
echo '<li><a href="';
echo $row[$i . 'url'];
echo '"></a></li>';
}
}
Mind you, this is pretty hacky... I would have just implemented it with 3 columns (maybe 4 using an autoincrement to sort) and then select the rows based on the user, emitting each row. That removes the 10 url limit.
Edit
For your second question, have a look at the PHP 'empty' function and break/continue the loop if the function returns true.
It would be a lot cleaner and easier to change your database setup a little bit. You could have two tables:
users
id: a unique ID for each user, probably an auto increment int of some sort
full_name: just as you've used it in your table
quick_links
id: quick link id, probably an auto increment int (or you could do a primary index on user_id+order)
user_id: the user ID to tell us who this quick_link belongs to
name: the name of the quick link
url: the url of the quick link
order: what order to show this link in
Then you can simply do something like
$userid_result = mysql_query(
"SELECT `id` from `users` WHERE `full_name` = $loggedin;"
);
$row = mysql_fetch_row($userid_result);
$userid = $row[0];
$links_result = mysql_query(
"SELECT * from `quick_links` WHERE `user_id` = $userid ORDER BY `order` ASC;"
);
while($quick_link = mysql_fetch_object($links_result))
{
printf("<li>%s</li>", $quick_link->url, $quick_link->$name);
}
Of course you'd need some error checking in there, but that gives you an idea.
You need to put some double quotes around your select statement:
$result = mysql_query("SELECT * FROM `links` WHERE `full_name`='$loggedin'") or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<li><a href="';
echo $row['1url'];
echo '"></a></li>';
}
while ($row = mysql_fetch_array($result))
{
$full_name = array_shift($row);
for ($i = 0; $i < 10; ++$i)
{
echo '<li><a href=' . htmlspecialchars(array_shift($row)) . '>';
echo array_shift($row);
echo '</a></li>';
}
}
array_shift returns the first element from an array and removes it from the array at the same time. So the code above removes the full_name field from the record and then iterates over the rest of the record, removing and printing a URL and its corresponding name on each iteration.
htmlspecialchars is used to ensure that a valid a-tag is created. Depending on where the name of the link comes from, it should also be used on the name of the link.
You SQL query needs to be passed as a string enclosed in "...":
$result = mysql_query( "SELECT * FROM `links` WHERE `full_name`='$loggedin'" )
or die (mysql_error());
$i = 0;
while($row = mysql_fetch_array($result)){
$attributeURL = $i . 'url';
$attributeName = $i++ . 'name';
echo '<li>'
. '' . $row[ $attributeName ] . '
. '</li>'
;
}

Categories