I'm trying to display data from database and it is important to me that this output is placed on different sides of website. I used php to connect to database, and ajax jquery to refresh data because every 20second values change.
I tried to
echo <div styles='position: absolute; top: 0px' class='text'>{$row['id']}</div>
in a foreach loop but when I do this all 6 of my id's are stacked on top each other.
Making <div> outside loop was unsuccessful too. I guess my problem is in reading data from database because I read all at once but I don't know any other way to do this except wrtiting 6 connection files to gather only the one value that I want to display and then styling it, but I feel like there is smarter way of doing this.
This is my code. Just want to say this is my first contact with php.
<?php
$hostname = "someinfo";
$username = "someinfo";
$password = "someinfo";
$db = "someinfo";
$dbconnect = mysqli_connect($hostname,$username, $password,$db) or die("cant");
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$sensor_names = array();
$query2 = mysqli_query($dbconnect,"show tables");
while($row2 = mysqli_fetch_array($query2)){
if($row2[0] == 'sensors' or $row2[0] == 'measurments'){
break;
}
else{
array_push($sensor_names,$row2[0]);
}
}
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, max(dev.id), dev.temprature, dev.date from sensors s, `{$sensor_names[0]}` dev where s.id=dev.sensor_id gro
up by s.id, s.sensor_name order by s.id asc");
while($row = mysqli_fetch_array($query)){ //i konw this is ugly but this is working placeholder
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, dev.temprature, dev.date from sensors s, `{$sn}` dev where s.id=dev.sensor_id order by dev.id desc limit 1");
$row = mysqli_fetch_array($query);
echo "
{$row['id']}
{$row['sensor_name']}
{$row['temprature']}
{$row['date']}
<br>";
}
}
?>
This is off-the-cuff from a guy who hasn't touched PHP in a long while, so watch for major bugs. But the basic idea is like this: build the code in a variable, and when done, echo out the entire variable. Makes it easier to add the structure/formatting you want. Note that you can also stick in a style tag along with that code and blurp out the style along with the "table" (Personally, I wouldn't use a table for styling, this is just for demo).
Note: I didn't style the output so that it puts the data on either side of the page - I left that for you to do. It's basic HTML - divs, styles, maybe css grid or flexbox. The point is to create your CSS/HTML/PHP mashup in a string variable and output the entire thing when done.
$out = '<style>.cell_id{font-weight:bold;}</style>';
$out .= '<table><tr><th>Label 1</th><th>Label 2</th><th>Etc</th></tr>'; //<=== ADDED!
while($row = mysqli_fetch_array($query)){
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, etc. etc. etc.);
$row = mysqli_fetch_array($query);
$out .= "
<tr>
<td class='cell_id'>{$row['id']}</td>
<td>{$row['sensor_name']}</td>
<td>{$row['temprature']}</td>
<td>{$row['date']}</td>
</tr>";
}
}
echo $out;
Ok I think I got it. Cssyphus's answer got me thinking and I wrote something like that array_push($data, $row) and $data is two dimentional array that hold all data I need and now I can style it easily.
Related
This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 4 years ago.
I have been struggling with this PHP script on my personal web server for quite some time. No matter what I do, or what input I give the HTML form (this PHP script is the action page for that form), I end up with a page that looks like this:
view larger version
Below is my code, which is supposed to get a list of ids of the recipes with a tag matching the user's query, then display a quick overview of the matching recipes to the user, in table format:
<html>
<body>
<title>Recipe Database</title>
<h1>recipe finder</h1>
</body>
</html>
<?
$servername = "localhost";
$username = "root";
$password = "xxxx";
$con = mysqli_connect($servername, $username, $password, "recipes");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tag = $_POST["keyword"];
$query = mysqli_query($con, "SELECT id FROM recipes WHERE tag1 LIKE '$tag'");
$query2 = mysqli_query($con, "SELECT id FROM recipes WHERE tag2 LIKE
'$tag'");
$query3 = mysqli_query($con, "SELECT id FROM recipes WHERE tag3 LIKE'$tag'");
$result = mysqli_fetch_array($query);
$result2 = mysqli_fetch_array($query2);
$result3 = mysqli_fetch_array($query3);
$list = array_merge($result, $result2);
$list = array_merge($list, $result3);
if ($list[0] != ""){
echo "<table>";
for ($i = 0; $i < count($list); $i++) {
echo "<tr>";
$detailquery = mysqli_query($con, "SELECT * FROM recipes WHERE id LIKE
\"$list[$i]\"");
$details = mysqli_fetch_array($detailquery);
print "<h3>" . $details[1] . "</h3>";
print "<p>" . $details[2] . " minutes</p>";
print "<p>" . $details[3] . " servings</p>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No recipe with that tag was found. Try a different tag.";
}
?>
I tested it on several different online syntax checkers and it came out clean. Yes, all other PHP scripts are running fine on my server. Yes, all the other PHP scripts are reading and writing to this database and others on my server without error. Yes, I did try wrapping body and html around the PHP script, it makes no difference. Yes, I have checked for unpaired quotation marks and apostrophes, there are none. Yes, I have tried storing the various queries in separate variables, that did not affect anything.
Any help would be appreciated, I am truly stuck on this one. Thank you!
Oops, it looks like I forgot to have the extended tag
<?php
instead of the short one without "php". My bad for being so oblivious.
Noob alert here. I'm just (trying to) teaching myself PHP because I need it on my internship job. Now I am creating a survey and I am trying to use while loops to show the questions and their respective answers onto my XAMPP. I am using this code:
<?php
mysqli_select_db($conn, "surveyordina");
//code hier schrijven
$sql = "SELECT questions_body FROM survey_questions where subthema_id = 1";
$sql2 = "SELECT answer_body FROM survey_answers where answer_id = 1 or answer_id = 2 or answer_id = 3";
$result = mysqli_query($conn, $sql);
$result2 = mysqli_query($conn, $sql2);
if(mysqli_num_rows($result2) > 0){
while($row = mysqli_fetch_assoc($result)) {
echo "<br>" ."Vraag: <br>" . $row["questions_body"]. "<br>";
while($row_answer = mysqli_fetch_assoc($result2)) {
echo $row_answer["answer_body"]. "<br>";
}
}
}
else{
echo "No results";
}
Now the returning part of this code looks like this:
Vraag:
Is the organization aware of where all the personal data is stored? Be it on-site or in the cloud, hosted by the company or by a third party?
Yes
No
I don't know
Vraag:
Is the organization able to locate and find personal data of a particular data subject?
Vraag:
Does the organization have technology in place to return all personal data on a given data subject, given a single search from personnel?
Vraag:
testerino kekkerino
I am trying to get the Yes, No, and I don't know parts under each and every question but only seem to get it under one of the questions.
Is there a method to return the whole answer part under each question? If so, am I on the right path or am I doing something completely wrong?
Thanks in advance.
Once you hit the end of a result-set, mysqli_fetch_assoc() doesn't just keep cycling through. So you're hitting the end of the $result2 set within the first outer loop, and then that's it, there are no more results to fetch.
You should fetch all of the $result2 results outside of the $result loop, assign the results to a variable, and then loop through that array within the $result loop.
Something like:
if(mysqli_num_rows($result2) > 0){
$result2Set = mysqli_fetch_all($result2, MYSQLI_ASSOC);
while($row = mysqli_fetch_assoc($result)) {
echo "<br>" ."Vraag: <br>" . $row["questions_body"]. "<br>";
foreach($result2Set as $row_answer) {
echo $row_answer["answer_body"]. "<br>";
}
}
}
Being a huge PHP newbie I find myself stuck here.
I have an HTML table for a videogame store filled with elements taken from my database.
The point is, I want to be able to add a link to the game title. Moreover I want the link to direct to some "gamePage.php", a php page used for every videogame but of course showing different infos for each game (title, console etc).
The fact is that not only I can't add the hyperlink, but I have no clue on how to carry the videogame infos when I click on a link (even managing to add the link, all I would manage to do would be redirecting the user to a blank gamePage.php with no title).
This is the code I use to fill the table (the restore function fills my table):
<html>
<body>
<div>
<table width = "550px" height = "300px" border="2" >
<tr bgcolor="#5f9ea0">
<td>Title</td>
<td>Console</td>
<td>Genre</td>
<td>Price</td>
</tr>
<?php
$conn = #pg_connect('dbname=project user=memyself password=project');
function search(){
<!-- Work in progress -->
}
function restore(){
$query = "SELECT v.Title , c.Consolename , g.Genrename , v.Price
FROM vg_shop.videogame v, vg_shop.console c, vg_shop.genre g
WHERE v.Console=c.IDConsole AND v.Genre=g.IDGenre";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
}
}
<!-- some code -->
</body>
</html>
At first i tried to do this
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
But all I get is a white page, there's some syntax error I don't get.
And, even if it worked, I still can't carry at least the videogame PID through the gamePage link
so, you're managing to go to gamepage.php somehow.
So you need to add some sort of identifier to your link you that you could do some query on the gamepage.php by using that identifier to get info for that particular game.
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td><a href='gamePage.php?id=%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['id'], $myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
Note: I assume that you're picking $myrow['id'] from database as well.
now on your gamepage.php do following.
$id = $_GET['id'];
$sql = "SELECT * FROM vg_shop.videogame WHERE `id` = $id";
$result = pg_query($sql);
if($result){
$result = pg_fetch_assoc($result):
//...
// echo "Name: ".$result['Title'];
// other fields
}
$result will have all info about that particular game that was clicked, you can display all as you want.
Cheers :)
I have the following code that works by outputting as a link ( the link comes from a field in my database) I wish to do the same for the code below, however i cannot get it work, here is the example of what I have that works, and the code that i wish to make output as a link:
Working Code what I want it to look like
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM adrenaline WHERE title LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br> '. $row['title'] .'';
}
}
?>
And the code that i have at the moment, it works by be manually typing in the hyper link, however I wish to make it take the link from the database like the example above
//query the database
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
//ferch the results / convert results into an array
WHILE($rows = mysql_fetch_array($query)):
$title = $rows['title'];
echo "<a href='shard.php'>$title</a>";
endwhile;
?>
Many thanks!
I am not 100% certain if this is what you meant to ask... let me know in comments:
<?PHP
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
if(mysql_num_rows($query) >= 1) {
while($rows = mysql_fetch_array($query)) {
echo sprintf("%s", $rows["description"], $rows["title"]);
}
} else { echo "No hobbies found."; }
?>
I believe you might have faced some syntax issues while dealing with quotes parsing a variable in <a html tag. Consider using sprintf something like in my example.
I have also added a mysql_num_rows() just in case and you can see its a good fail-safe method incase there are no rews found on any select query.
IMPORTANT: STOP using mysql_ functions because its deprecated from new PHP versions. Use PDO or mysqli instead.
I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit