Updating dynamic links from database results - php

I'm playing around with PHP a bit and am trying out dynamic links. My problem is that the corresponding ID is not correctly to the URL with my code, so I have the same link everytime.
Here is what I have:
<?php
$connection = mysqli_connect('localhost', 'root', 'password');
mysqli_select_db($connection, 'filme');
$query = "SELECT * FROM filme";
$result = mysqli_query($connection, $query);
$filmID = mysqli_fetch_assoc($result);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row['Name'] . " - " . $row['Preis'];
}
$chunks = array_chunk($array, 4);
$filmID = mysqli_fetch_assoc($result);
echo "<table class='filme'>";
foreach ($chunks as $chunk){
echo '<tr>';
foreach ($chunk as $val) {
?><td><?php echo $val; ?> </td><?php
}
echo '</tr>';
}
echo "</table>";
mysql_close();
?>
What I'm trying to do is display a table with four columns, that in every cell has a string in the format of "Film name - Price" and this string should be a link that leads to the page with the according ID. This code does display my four column table, but it is missing the first item of my database and the ID is the same for every link, namely the ID of that first film that is missing. So every URL looks like this:
http://localhost/dvd.php?Film_ID=1000
But the film with the ID 1000 is not even listed. I thought about putting that nested foreach loop in a while loop with
while($filmID = mysqli_fetch_assoc($result)){
...
}
But with that I get a blank page.
I have just about no experience with php, so sorry if I'm missing something really obvious.

You are going about this the wrong way. There's no link here between the contents of $array and $filmID. Indeed, $filmID is probably empty because you've already run through your result set earlier. Imagine your database result set is like a stack of papers. Each call to fetchAssoc() reads one sheet of paper, and sets it aside. Once you reach the end of the result set, there's nothing left to read, so your next calls will fail. You need to do all your database fetch in a single loop. As well, you should not be using mysql_close() with mysqli.
<?php
$connection = mysqli_connect('localhost', 'root', 'password');
$connection->select_db('filme');
$query = "SELECT * FROM filme";
$result = $connection->query($query);
$array = array();
while($row = mysqli_fetch_assoc($result)){
$array[] = $row;
}
$chunks = array_chunk($array, 4);
echo "<table class='filme'>";
foreach ($chunks as $chunk){
echo '<tr>';
foreach ($chunk as $film) {
?><td><?php echo "$film[Name] - $film[Preis]"; ?> </td><?php
}
echo '</tr>';
}
echo "</table>";
mysqli_close();
Or, better yet, just use the more modern PDO library:
<?php
$connection = new PDO("mysql:host=localhost;dbname=filme", "root", "password");
$query = "SELECT `Film_ID`, `Name`, `Preis` FROM filme";
$result = $connection->query($query);
$chunks = array_chunk($result->fetchAll(PDO::FETCH_ASSOC), 4);
?>
<table class='filme'>
<?php foreach ($chunks as $chunk):?>
<tr>
<?php foreach ($chunk as $film):?>
<td>
<?=htmlspecialchars("$film[Name] - $film[Preis]")?>
</td>
<?php endforeach?>
</tr>
<?php endforeach?>
</table>
Note this code is much more efficient and easier to read due to use of alternative syntax and short echo tags to keep PHP and HTML mixing to a minimum. Ideally your PHP would be in a totally separate file.

Related

SQLite and PHP displaying data from using array

I wanna display columns from specific table and I did it BUT im totally new to this, and I'm trying to build this site for myself and community I have so they can redeem gear from points they get by posting. Script works fine but I wanna get rid of this stuff Array аnd arrows, you can see it on screenshot I've provided, I want to display only username and points but not whole thing.
https://gyazo.com/1cbb85765ae3fd21efa76215b7042329
here is a code that I'm using:
<?php
$db = new SQLite3('phantombot.db');
$sql = "SELECT variable, value FROM phantombot_points";
$result = $db->query($sql);//->fetchArray(SQLITE3_ASSOC);
$row = array();
$i = 0;
while($res = $result->fetchArray(SQLITE3_ASSOC)){
if(!isset($res['variable'])) continue;
$row[$i]['variable'] = $res['variable'];
$row[$i]['value'] = $res['value'];
$i++;
}
print_r($row);
?>
You can create the table for that
<table>
<tr><th>Username</th><th>Points</th></tr>
<?php foreach($row as $datum): ?>
<tr>
<td><?php echo $datum['variable'];?></td>
<td><?php echo $datum['value'];?></td>
</tr>
<?php endforeach;?>
</table>

PHP - output associate array into HTML <div>s with labels/headings

I have a PHP function that returns a single row from a localhost MySQL table like so:
<?php
//include database connection process
require_once("includes/conn.inc.php");
//prepare statement
$stmt = $conn->prepare("Select * FROM races WHERE raceID = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
?>
What I would like to do with this array is output the data from the individual fields in their own HTML <div> or <p> with a heading indicating what they mean in a separate div. I currently user the print_row method that outputs everything in one. All the data I want is there, but I'd like it separated out into name/value paragraphs or divs.
//what I currently have
<?php
print_r($row);
?>
Is there a way to do this?
Thanks in advance,
Mark
I didn't understand the question very well but I think I understand what you need.
Use while to iterate trough each row.
while($row = $resultDesc->fetch_assoc())
{
echo '<p><strong>Description:</strong></p> ';
echo '<p>'. $row['description'] . '</p>';
}
That's not the exact solution but atleast shows you the path.
You can use foreach
<?php foreach ($row as $key => $val): ?>
<p><strong><?php echo $key; ?>:</strong></p>
<p>
<?php
//output relevant attribute
//of query run on page load
echo $val;
?>
</p>
<?php endforeach; ?>

Shows Table and Values Using Drop Down

In this application I have a drop down so you can select what table you want to view. Using Ajax I push the variable $tbl as an integer and the code below prints out the table that corresponds with that integer. Something is not working though and I need an extra pair of eyes to help debug.
if($tbl == 9){$table = "person";}
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$query = mysqli_query($conn, "SELECT * FROM $table ") or die(mysqli_error($conn));
if($query){
echo '<table border="1"><thead><tr>';
$colnames = array();
while ($finfo = mysqli_fetch_field($query)) {
$name=$finfo->name;
array_push($colnames, $name);
echo "<th>".$name."</th>";
}
mysqli_free_result($query);
echo '</tr></thead><tbody>';
$count = 0;
echo $colnames[$count]; // this test prints the correct column name but it ends up being printed OUTSIDE the table for some reason
while ($row = mysqli_fetch_array($query, MYSQLI_BOTH)){
echo '<td>'.$row[$colnames[$count]].'</td>';
$count++;
}
echo "</tbody></table>";
}
The last while loop is suppose to echo out each field value but it isn't executing <tbody> is left blank.
You called mysqli_free_result($query) too early. So by the time you called mysqli_fetch_array, the sql result was already gone. Move mysqli_free_result after the last loop.
I'm not sure whether it's a typo or that the following is where the problem lies, but you're missing opening and closing <tr> tags around the column names after <tbody> and before </tbody>. This may help explain why stuff is being printed apparently "outside" the table.

Selecting from database error mysqli_query / mysqli_fetch_array

I'm trying to get this information out of the database:
$query = "SELECT * FROM station_control WHERE station_no > 0 ORDER BY station_ord";
it then says it expects parameters in these two lines:
$station_result= mysqli_query($query);
$num= mysqli_fetch_array($station_result);
this is what I want to output, basically to pull every station name from the database called station_ord and the names are under station_name:
$i=0;while ($i < $num) {
$station_name1=mysqli_result($station_result,$i,"station1_name");
$station2_name= mysqli_result($station_result, $i,"station2_name");
$station3_name= mysqli_result($station_result, $i,"station3_name");
$station4_name= mysqli_result($station_result, $i,"station4_name");
$station5_name= mysqli_result($station_result, $i,"station5_name");
echo "<b>
$station1_name $station2_name2</b> <br>
$station3_name<br>
$station1_name4_name<br>
$station5_name<hr> <br>";
$i++;
}
I haven't put in the station_name yet as im confused to where and how I configure that.
Any ideas how to help?
Not sure what you try to do, but try
<?php
$station_result= mysqli_query($query);
$records = mysqli_fetch_array($station_result);
foreach ($records as $record) :?>
<b><?php echo $record['station_name']; ?></b><br/>
<?php endforeach; ?>
ref : http://ch1.php.net/manual/en/mysqli.query.php
and http://www.php.net/manual/en/mysqli-result.fetch-array.php for examples
Something like this should work.
$station_result= mysqli_query($query);
$results= mysqli_fetch_array($station_result);
foreach ($results as $row) {
// echo whatever you want here
echo $row['station_name'];
}

Using php to fill a <select> on webpage. Looking for a faster load time

I added this :
<select>
<option value=""></option>
<?php include 'connect/config.php'; ?>
<?php include 'connect/opendb.php'; ?>
<?php
$query = $db->query('SELECT type FROM card_type');
$rows = $query->fetchAll();
foreach($rows as $row) {
print '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
?>
<?php $db =null ?>
</select>
to my page and now it's takeing about 5 seconds longer to load the page.
Is there a more effecient way to fill a option box from a database?
These are some issues in your code that affects performance:
You should not call print for each row of your table. That penalizes
performance (if the server is not caching the output) as everytime
you call print you will be sending bytes across the net which is a
costly operation that is better be done once for one big chunk of
data rather than many times for small chunks of data , that is
the reason web servers will often cache all your PHP output prior to
sending it to the browser.
You should pass by reference the array value when traversing the
array with foreach, to avoid the copy of a variable in each
iteration of the loop.
Echo with commas, not periods. If
you use periods, PHP has to concatenate the string before it
outputs. If you use commas, it just outputs them in order with no
extra processing.
You should use echo instead of print(). As a language construct rather than a
function, echo has a slight performance advantage over print().
So this is your code with points 2, 3 and 4 above corrected, thus assuming your web server is caching output:
<?php
$query = $db->query('SELECT type FROM card_type');
$rows = $query->fetchAll();
foreach($rows as &$row) {
echo '<option value="', $row['type'] ,'">' ,$row['type'] , '</option>';
}
?>
and this is your code with point 1 and 2 above corrected, thus assuming your web server is not caching the output:
<?php
$query = $db->query('SELECT type FROM card_type');
$rows = $query->fetchAll();
$out = '';
foreach($rows as &$row) {
$out .= '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo $out;
?>
Right now, you're putting the entire database table into a php array. If your table is large, this may cause the delay in response.
Try this instead, for the part where you fill the <select>:
<?php
$query = $db->query('SELECT type FROM card_type');
while($row = $query->fetch_array()) {
print '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
?>
Try this one..
<select>
<option value=""></option>
<?php
include 'connect/config.php';
include 'connect/opendb.php';
$query = $db->query('SELECT type FROM card_type');
$rows = $query->fetchAll();
$select_option = '';
foreach($rows as $row) {
$select_option .= '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo $select_option;
unset($db);
?>
</select>

Categories