I have a mysql table in which contains video titles, video embed html, video description, and video thumbnails. I want it to output the first entry as;
$result = mysqli_query($con,"SELECT * FROM entries");
while($row = mysqli_fetch_array($result)) {
echo $row['title'];
echo $row['html'];
echo $row['desc'];
}
and after that, I would like it to output the next five entries as
$result = mysqli_query($con,"SELECT * FROM entries");
while($row = mysqli_fetch_array($result)) {
echo $row['title'];
echo "<a href='". $row['id'] . "'><img src='" . $row['thu'] . "'></a>";
}
however I have no idea how to do this. I am kind of a newb when it comes to mysql. Any help would be appreciated.
I have looked at other similar questions but none of them really fit the bill.
Poor man's solution would be something like:
$result = mysqli_query($con,"SELECT * FROM entries");
$first = true;
while($row = mysqli_fetch_array($result)) {
if ($first) {
echo $row['title'], $row['html'], $row['desc'];
$first = false;
continue 2;
}
echo $row['title'], "<a href='{$row[id]}'><img src='{$row[thu]}'></a>";
}
(As explained in PHP chatroom)
Since mysqli_fetch_array() gets you a row, you can use it before the while() without a problem like this
$result = mysqli_query($con,"SELECT * FROM entries");
$row = mysqli_fetch_array($result);
echo $row['title'];
//etc.
while($row = mysqli_fetch_array($result)) {
echo $row['title'];
echo "<a href='". $row['id'] . "'><img src='" . $row['thu'] . "'></a>";
}
Track it with a sentinel value
$i = 0;
while($row = mysqli_fetch_array($result)) {
if($i == 0){
//first iteration
echo $row['title'];
echo $row['html'];
echo $row['desc'];
}else{
echo $row['title'];
echo "<a href='". $row['id'] . "'><img src='" . $row['thu'] . "'></a>";
}
$i++;//increment value
}
Related
What I need to make happen:
I am populating divs with data from mySQL based on the item ID. I need to create variables to be called into the divs such as $tip_ + $id which results in:
$tooltip_1
$tooltip_2
$tooltip_3
What I have done so far:
$query = 'SELECT * FROM top_tips WHERE type = "aw"';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
$tip_ID = $row[0];
$tip_text = $row[2];
$tip_link = $row[3];
$tooltip = "<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$tip_text . " <a href='" .$tip_link . "'>read more ...</a>";
echo $tooltip;
}
Where I am stuck:
What is the most efficient way to output $tooltip + $tip_id so the variables can be called into the respective divs?
You would do it like this:
while ($row = mysqli_fetch_row($result)) {
$tip_ID = $row[0];
$tip_text = $row[2];
$tip_link = $row[3];
$tooltip = "tooltip_{$tip_ID}";
$$tooltip = "<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$tip_text . " <a href='" .$tip_link . "'>read more ...</a>";
echo "tooltip_{$tip_ID}";
}
That will give you variables such as $tooltip_1, $tooltip_2 and so on. That said, I recommend you use an Array for this.
Added For foreach for your Code..
<?php
$query = 'SELECT * FROM top_tips WHERE type = "aw"';
$result = mysqli_query($link, $query);
while ($results = mysqli_fetch_row($result)) {
foreach($results as $row){
$tip_ID = $row[0];
$tip_text = $row[2];
$tip_link = $row[3];
$tooltip = "<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$tip_text . " <a href='" .$tip_link . "'>read more ...</a>";
echo $tooltip;
}
}
?>
Hope you need this solution.. im confused in your question.
You can create an array of $tooltips like so:
$tooltip[] = "<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$tip_text . " <a href='" .$tip_link . "'>read more ...</a>";
It seems that you care about efficiency and how to concatenate your $tooltip_ and $tip_ID. First about efficiency, I always learn : When you are fetching results through a loop, never creates variables. Always outside !
In your case, you could create it like this before fetching the results :
<?php
$tooltip_array = array(); //Future array containing your $tooltip_1, $tooltip_2...
$query = 'SELECT * FROM top_tips WHERE type = "aw"';
$result = mysqli_query($link, $query);
Then, in your loop you can push each tooltip onto your array like this :
while ($row = mysqli_fetch_row($result)) {
array_push($tooltip_array,"<div class='tooltip-close'><a href='#' class='close'>×</a></div>" .$row[2] . " <a href='" . $row[3] . "'>read more ...</a>");
}
Finally you can echo this out with a foreach loop :
// Iterating through the values
foreach($tooltip_array as $value)
{
echo $value;
}
I wanted to post the working solution I ended up using for anyone reading this thread.
$query = 'SELECT * FROM tool_tips WHERE tip_type = "aw"';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
$tooltip_array[$row[0]] = "<div class='tooltip-close'><a
href='#' class='close'>×</a></div>" .$row[2]. "<a href='" .$row[3]. "'>read more ...</a>";
}
Then I call the individual tooltips like:
<?php echo $tooltip_array[12];?>
I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>
I have just created a pagination function for a travel company. There are two things I want to change that I can't figure out.
Each trip has a date. What i want to be able to do is stop the trip from displaying in the list one the day of the trip and all subsequent days. I have a rough idea, but that doesn't seem to work.
if (date($row['date']) getdate()) {
// echo trip info here
}
-2. After each of the trips in the list there is a seperator (is that the right word?) to separate each trip's info. On the last trip if the page I don't want that seperator. I have no clue how to do this :/
Thanks in advance for any help & advice.
<?php
if (isset($_GET["p"])) { $page = $_GET["p"]; } else { $page=1; };
$start_from = ($page-1) * 4;
$sql = "SELECT * FROM destinations ORDER BY date ASC LIMIT $start_from, 4";
$result = mysqli_query ($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo "<div class='row'>";
echo "<div class='col-md-4 col-sm-4'>";
echo "<img src='" . $row ['img'] . "' alt='' class='img-responsive'>";
echo "</div>";
echo "<div class='col-md-8 col-sm-8'>";
echo "<h2><a href='" . $row ['url'] . "'>" . $row ['name'] . "</a></h2>";
echo "<ul class='blog-info'>";
echo "<li><i class='icon-calendar'></i> " . date("d/m/y", strtotime($row['date'])) . "</li>";
echo "</ul>";
echo $row ['description'];
echo "<a class='btn theme-btn' href='" . $row ['url'] . "'>View Details <i class='icon-angle-right'></i></a>";
echo "</div>";
echo "</div>";
echo "<hr class='blog-post-sep'>";
}
$sql = "SELECT COUNT(trip_id) FROM destinations";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
$total_pages = ceil($total_records / 4);
echo "<div class='text-center'> <ul class='pagination pagination-centered'>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<li><a href='routea.php?p=".$i."'>".$i."</a></li>";
};
echo "</ul></div>";
mysqli_close($con);
?>
Change your SQL to filter out the unwanted trips:
SELECT * FROM destinations
WHERE date < CURRENT_DATE()
ORDER BY date ASC
LIMIT $start_from, 4
You can solve it with CSS:
hr.blog-post-sep:last-of-type {
display: none;
}
I have this following code in a switch statement since the query can vary based on screen-name(1 word), full name (2 words...maybe 3), or the email address which "explode"'s to 3 words (I put it back together later, no biggy). However, cannot locate the problem in the following code:
$query = "SELECT * FROM personal WHERE FirstName='$searchName' OR LastName='$searchName' OR Email='$searchName' OR displayName='$searchName'";
$result = mysql_query($query) or die(mysql_error());
echo "<center><table border='1' width='70%'>";
if (mysql_num_rows($result)) {
$row = mysql_fetch_assoc($result);
$myBuddy = $row['FirstName'].
" ".$row['LastName'];
$picName = $row['FirstName'].$row['LastName'].$row['RecNum'];
if (file_exists('../members/'.$picName.
'/profile.jpg')) {
$picLine = "<img src = '../members/".$picName.
"/profile.jpg' alt='profile' height='100' width='100' />";
}
echo "<tr>";
echo "<td style='text-align:center'>".$picLine.
"</td>";
echo "<td style='text-align:center; color:red'>".$myBuddy.
"</td>";
echo "<td style='text-align:center'><input type='button' value='Add Buddy'></td>";
}
echo "</table>";
break;
Problem is, I have several people in my MySql database with the same last name (Jones), however in the code above only returns the first occurance of someone with the last name Jones. Trying to return them all, not just one. I know I am just overlooking something small & stupid - been doing php/mysql for 2 years now - never had to do a search page before. Any help is greatly appreciated.
while ($row = mysql_fetch_assoc($result)) {
//...
//use $row
}
instead of
$row = mysql_fetch_assoc($result);
You have too loop the results, like in the following example:
echo "<center><table border='1' width='70%'>";
if (mysql_num_rows($result) )
{
while($row = mysql_fetch_assoc($result)) {
$myBuddy = $row['FirstName'] . " " . $row['LastName'];
$picName=$row['FirstName'].$row['LastName'].$row['RecNum'];
if (file_exists('../members/' . $picName . '/profile.jpg'))
{
$picLine = "<img src = '../members/" . $picName .
"/profile.jpg' alt='profile' height='100' width='100' />";
}
echo "<tr>";
echo "<td style='text-align:center'>" . $picLine . "</td>";
echo "<td style='text-align:center; color:red'>" . $myBuddy . "</td>";
echo "<td style='text-align:center'><input type='button' value='Add Buddy'></td>";
}
echo "</table>";
break;
}
Above, I have used a while loop.
while($row = mysql_fetch_assoc($result)) {
// code
}
I have a query to bring results from my database. It works... until there are more than 2 results that it, then it just repeats some results before adding in new ones.
I know it will be because my query is fairly poor, can anyone advise me?
The idea is
connect to database with photo links
get the default user picture as $profile_main
join the words "photo_" with the default picture number and call it
$answer (ex: column 'photo_1' in database)
now check the database again and get the results for $answer and
output all information from that database column.
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
$result2 = mysqli_query($con,"SELECT $answer FROM tbl_photos");
while($row = mysqli_fetch_array($result2))
{
echo "<img src=\"" . $row[0] . "\">";
}
}
mysql_fetch_row returns numerical indexes instead of column names (so ['default'] just won't work)...
This is how I would do it if I'm understanding you correctly:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_assoc($result))
{
$answer = $row['photo_'.$row['default']];
echo "<img src=\"" . $answer . "\">";
}
Anyway, this is assuming default and photo_x are in the same row.
If you want only one result for a photo then you can use LIMIT like this
SELECT $answer FROM tbl_photos LIMIT 1
First, both loops you set same $row variable. Use 2 different variable names so that the results don't get mixed up.
Second issue is that you have you have 2 loops , so it will show all results each time. You need to break in the second loop. Like this:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
$result2 = mysqli_query($con,"SELECT $answer FROM tbl_photos");
while($row2 = mysqli_fetch_array($result2))
{
echo "<img src=\"" . $row2[0] . "\">";
break;
}
}
Or by using only one query, it would be much more efficient:
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$profile_main = $row['default'];
$answer = "photo_" . $profile_main;
echo "<img src=\"" . $row[$answer] . "\">";
}
You only require 1 query.
TRY
$result = mysqli_query($con,"SELECT * FROM tbl_photos");
while($row = mysqli_fetch_array($result))
{
$photo = "photo_" .($row['default'];
echo "<img src=\"" . $photo . "\">";
}