php concatenate to display data from another file - php

So I've got some rows in a table that I want to use to concatenate. I also have a file that runs a query to count comments. I want to pull that number from that file.
I was doing it with straight html but my website is getting too big so I'm trying to make it dynamic with php and mysql.
So with my Html its hard coded and works:
<?php include_once("comments/post_title/tpost_title.php") ?>
So I thought I could just concatenate it to be the same, but for some reason my web browser (chrome) thinks its a comment.
Php:
$query = "SELECT post_title FROM sessions";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
echo "<a href=\"#" .strip_tags("{$row['post_title']}"). "\">read comment";
echo "<?php include_once(\"comments/" .strip_tags("{$row['post_title']}")."/t". strip_tags("{$row['post_title']}"). ".php\") ?>";
echo "</a>";
}
I've read about "#file_get_contents" but my understanding of it is limited. As I understand it has to be set to a variable and then I would have to insert that into my while loop. But I get lost in how the variable changes to the next row in my table to pull the next post_title.
I guess another option would be to put the query that's in that file that counts comments into this loop, but then I'd have to put a variable into the query. (Is that "good" coding?) Say for instance:
$query = "SELECT post_title FROM sessions WHERE session = 'variable';
Thanks in advance for the help and insight.

To read the file in the loop, you need:
while($row = mysql_fetch_assoc($result))
{
echo "<a href=\"#" .strip_tags("{$row['post_title']}"). "\">read comment";
include_once("comments/" .strip_tags("{$row['post_title']}")."/t". strip_tags("{$row['post_title']}"). ".php");
echo "</a>";
}
If the file you read isn't PHP but straight HTML, then you can use readfile() instead of include(). The syntax is the same.
To be sure, though, it would be better something like,
$file = "comments/" .strip_tags("{$row['post_title']}")."/t". strip_tags("{$row['post_title']}"). ".php";
if (file_exists($file))
readfile($file);
else
echo "ERROR";

Related

php mysql show result one after another

I wanna build a presence check for our choir in the style of tinder but not as complex.
The database contains names and file paths of pictures of the members. When you click on the "present" or "not present" button, the next picture and name should be shown. In the background, the database table should be updated with true/false for presence. (this will be done later)
My problem is that it almost works, but instead of showing one member, it shows all members with their pictures in one single page.
I understand that I could fire with Javascript to continue and paused php-function but I don't get the clue how.
I tried "break" in the php and call the function again but that didn't work.
<?php
$conn = new mysqli(myServer, myUser, myPass, myDbName);
$sql = "SELECT * FROM mitglieder";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img class='pic' src='" .$row["folder"]. "/" .$row["img"]. "'><br>" ;
echo "<div id='name'>" .$row["vorname"]. " " .$row["name"]. "</div> <br>";
echo "<img src=''img.png' id='present' onclick='isPresent()'>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<script>
$( document ).ready(function() {
console.log("Ready");
);
</html>`
You can use php function
mysqli_fetch_all()
assign it on the variable outside the while loop and loop or access the indexes in your code.
For Example:
$data = mysqli_fetch_all();
echo $data[0]['name'];
foreach($data as $item)
{
echo $item['name'];
}
You need a way to establish a "state" between your web page and the PHP backend so that you can step through the data. I suggest something like this:
Use an auto-increment integer primary key for the database. That way you can access the data in index order. Let's name the column id
Have your JS code send a form variable - named something like LAST_ID to the PHP in your get. i.e http://someurl.com/script.php?LAST_ID=0
On your first call to the server, send LAST_ID = 0
In your PHP code, fetch the value like this: $id = $_GET('LAST_ID');
Change your SQL query to use the value to fetch the next member like this:
$sql = sprintf("SELECT * FROM mitglieder where id > %d limit 1", $id); That will get the next member from the DB and return only 1 row (or nothing at the end of data).
Make sure to return the id as part of the form data back to the page and then set LAST_ID to that value on the next call.
You can use a HTTP POST with a form variable to the server call that sets that member id to present (maybe a different script or added to your same PHP script with a test for POST vs GET). I suggest a child table for that indexed on id and date.
I hope that puts you in a good direction. Good luck

My array won't echo a value for some reason

I have a database that holds thousands of structures. The structures are searchable by choosing the "area" first, then selecting the "block_number". My first page allows the user to select the area, the area is then passed through the url to the next page. The next page uses php to pull up the blocks in that area. I'm trying to echo the "area" and "block_number" in the results. The my query works just fine but, for some reason I can't display the "area" in the results. See the code below.
<?
include("conn.php");
include("pl_header.php");
$area = mysql_real_escape_string($_GET['area']);
$wtf = '$area';
?>
<h3>Choose A Block Number in<br> <?=$area?></h3><br>
<center>
<?php
$tblWidth = 1;
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
$i = 1;
// Check to see if any results were returned
if(mysql_num_rows($sql) > 0){
echo '<div class="redBox extraIndent">';
// Loop through the results
while($row = mysql_fetch_array($sql)){
echo ''. $row['area'] .''. $row['block_number'] .'';
if($i == $tblWidth){
echo '';
$i = 0;
}
$i++;
}
echo '';
}else{
echo '<br>Sorry No Results';
}
?>
</div>
</body>
</html>
My issue is where you see '. $row['area'] .' displays nothing, but the '. $row['block_number'] .' works just fine.
Your query is only selecting block_number.
Try changing:
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
To:
$sql = mysql_query("SELECT DISTINCT block_number, area FROM platform_locations WHERE area='$area'");
Edit: If you have this issue in the future try var_dump($row); to see what the array contains. This would show you that you only have access to the block_number and not the area.
Double edit: I didn't notice, but the other answer is right about the $area var- you've already got the $area saved, use that variable instead of the return from the DB as it's already in memory. If this could change per record, it'd be prudent to use the record's area variable to make your code more reusable. However, in this particular case, your SQL statement has the area in the where clause, so it wont vary unless you attempt to use portions of this code elsewhere.
Your SQL query is only selecting block_number, so that's the only field that will be in the $row array. You've already got area as a variable $area so use that, not $row['area'].

Printing out MySQL tables in HTML

I am currently using the code below to print out a MySQL table. However, when I am printing multiple rows the format is pretty ugly. What is a way or command I could create columns similar to the Tab key to make it more aesthetically pleasing?
$google= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($google)){
foreach($row as $cname => $cvalue){
print "$cvalue\t <tr>";
}
print "<br>";
}
The query is printed using user input. using the
<form action="google.php" method="post">
command. I am also looking for a way to print this table on the same page as the HTML page that I accept the user input.
Your code is pretty good and only needs HTML added to it to make it look nicer. Using tables (this has not been tested but it should work):
$google = mysqli_query($query) or die(mysqli_error());
echo '<table>';
while($row = mysqli_fetch_assoc($google)) {
echo '<tr>';
foreach($row as $cvalue) {
print '<td>'.$cvalue.'</td>';
}
echo '</tr>';
}
echo '</table>';
This is a quick and dirty way to output a MySQL table, but if you also want the names of the columns to show up, things get quite a bit trickier. Also, if your results contain special characters such as ">", this can mess up the output. If that happens, just look up the documentation for htmlspecialchars().
If you want this table to show up on the same page as your form, just create a submit button and check the value in PHP like so:
if (isset($_POST['SubmitButtonNameHere']) { ... }
I'm not sure of the structure of your form so this code might need to be different to determine whether the form has been submitted. You can put the code for creating the table inside of the curly braces and place the code for your form either above or below the if statement.
<tr> is an HTML element used to add rows to a <table> element. The <td> element adds cells to those rows. Also, your code was using mysql_*. This was changed to mysqli_* as the mysql prefix is deprecated in PHP. Hope this answers your question.
Just use this code instead :)
$google= mysql_query($query) or die(mysql_error());
echo "<table><tbody>";
while($row = mysql_fetch_assoc($google)){
foreach($row as $cname => $cvalue){
echo "<tr><td>".$cname."</td><td>".$cvalue."</td></tr>";
}
echo "</tbody></table>";
Done :)

Echo each record of a query result

I'm attempting to extract some data from a database and echo each result. The code below is code that I took from a textbook and then tried to modify to fit my own website that is hosted locally. I cannot see where I'm going wrong, no error messages are shown, just a blank screen when I run the scrip.
<?php #script 9.4 view top 5 recipients
// This script exctracts data from db and then displays each record in a table
DEFINE('SYSPATH','FOO');
require '../application/config/database.php';
require 'mysqli_connect.php';
$q = "SELECT alert_recipient as NAME
FROM alert
LIMIT 5;
";
$r = mysqli_query($dbc,$q);
// $dbc database connection comes from required mysqli_connect.php
if($r)
{
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo $row['name'];
}
}
else {
echo "<p>ERROR</p>".mysqli_error($dbc);
}
?>
The code looks okay except for your echo $row['name'];, note that you are selecting NAME, uppercase.
Change your echo statement to be:
echo $row['NAME'];
because field names quoted within $row array are case sensitive.
(Can't comment yet)
Maybe the script works but there is no results to display. Check your database.

PHP get some data from database then echo it out into a JS file

MYSQL table structure:
id , name , status , color
how can i use PHP to get some data from my database(mysql) ,the php script will look for table rows that have "good" in the "status" column. Then echo those rows which have good in status(P/S out into a JS file. It also get the color from each row (with status=good) and ptu it into javascript(jQUery)
I did a little research on how to use php to generate javascript.
Here's a php script, it's not working btw:
<?php
header("content-type: application/x-javascript");
include 'connect.php';
$sql = "SELECT * FROM users WHERE status ='good'";
$query = mysql_query($sql)or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array( $query )){
$rows[] = $row;
echo "$('a[href*=\"row[username]\"]').css('color', 'row[color]');\n";
}
?>
The out put is (which wont work):
$('a[href*="row[username]"]').css('color', 'row[color]');
The connect.php is working(connects to database) , just the script is not working.
(BTW: The file name of this is usercolor.js.php , is it correct?)
I hope someone could guide me.
Thanks and have a wonderful day.
echo "$('a[href*=\"row[username]\"]').css('color', 'row[color]');\n";
won't work. Try
$username = $row['username'];
$color = $row['color'];
echo "$('a[href*=\"$username\"]').css('color', '$color');\n";
or
echo "$('a[href*=\"{$row['username']}\"]').css('color', '{$row['color']}');\n";
see the manual for an explanation. Also, according to your mysql table structure, the column is called name and not username.

Categories