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
Related
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.
First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";
I'm trying to pass a value which is input into a box on one Php page (itinerary.php) into another Php page ('submit.php') so it can, from there, be saved into a database. But I can't quite figure out how to get it across. I've tried using GET as you can see from code below, but I am already using a GET statement to receive and acknowledge another value from that very same page 'submit'. I guess I am overcomplicating it, but my knowledge of Php is still pretty limited at this stage so any ideas would be appreciated!
This is an extract from the itinerary.php file (it sits within a Bootstrap/Html framework. Note the entry which contains the input box for the sequence number).
<h3><br>YOUR ITINERARY</h3>
<?php
//Display contents of itinerary
if(!empty($_SESSION['itinerary'])){
//Retrieve details of each location in array from database
$query = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $loc_id=>$value)
{$query.=$loc_id.',';}
$query = substr($query, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $query);
echo'<table><tr><th colspan="5">LOCATIONS IN YOUR ITINERARY</th></tr>';
//Display locations in array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$loc_id = $row['loc_id'];
echo"<br><td>{$row['loc_name']}</td></tr><br>
<td>{$row['loc_desc']}</td>
<td><p>Seq. No</p><input type=\"text\" size=\"3\" name=\"sequence\" value=????????>NOT SURE WHAT TO ADD INTO THIS LINE TO RETAIN THE INFO THAT IS INPUT</td>
<td><a href=remove_loc.php?value=$loc_id>Remove location</a><br></br></td>
</tr><br></table>";
}//while
print_r($_SESSION);
mysqli_close($db);
}//if
else {echo '<p><br>Your itinerary is empty.<br></p>';}
echo '<br><p>
<a href=submit.php?submit>Save itinerary</a>
<a href=clear_itin.php?clear>Clear itinerary</a>
Your details
Logout
</p>';
?>
And this is where I am trying to receive it and then use it in a SQL command to add to the database. (Again, this is within a Bootstrap framework)You can ignore the first SQL Insert statement as it is passing other info in successfully anyway..
<div class="row">
<div class="col-md-9">
<?php
if (isset($_GET['sequence'])){
$sequence = $_GET['sequence'];
}//if
if (isset($_GET['submit'])){
$query = "INSERT INTO itineraries (user_id, date_created) VALUES (".$_SESSION['user_id'].", NOW())";
$result = mysqli_query($db, $query);
$itinerary_id = mysqli_insert_id($db);
$retrieve_locs = "SELECT * FROM locations WHERE loc_id IN (";
foreach ($_SESSION['itinerary'] as $id=>$value)
{$retrieve_locs.=$id.',';}
$retrieve_locs = substr($retrieve_locs, 0, -1).')ORDER BY loc_id ASC';
$result = mysqli_query($db, $retrieve_locs);
//Store items in itin_locs db
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC)){
//This is the command I have been trying to use, commented out. The second one below this works fine, but obv doesn't input a sequence number.
//$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id, sequenceNo) VALUES ($itinerary_id, ".$row['loc_id'].", $sequence)";
$insert_locs = "INSERT INTO itin_loc (itinerary_id, loc_id) VALUES ($itinerary_id, ".$row['loc_id'].")";
$insert_result = mysqli_query($db, $insert_locs);
echo mysqli_error($db);
if ($insert_result === FALSE) {
die("Query failed!" . mysql_error() . $insert_locs);}
}//while
mysqli_close($db);
echo"<p>Your itinerary is saved!. Itinerary number is #".$itinerary_id."</p><br>";
$_SESSION['itinerary']= NULL;
echo '<p>
Your details
Logout
</p>';
}//if
else {echo '<p>Your itinerary is empty.<br></br></p>';}
?>
Use a form on your HTML page to hold all the input fields in the table.
Also instead of anchor "a" tag use a submit button to submit the form to other page.
Use some thing like:
Send value of submit button when form gets posted
First I want to explain my application:
I have created an application for my QA work. The application generates a document gets saved as a pdf and added to the server. I have a dynamic table in it that gets save to the database using the implode function separating it as with a comma in the same row as the test case on the database.
It all works fine, but when I want to view the test case I am having trouble to figuring out how to get it to display. I have read plenty of scenarios to use the explode but no luck...
<?php include 'app_database/database.php'; ?>
<?php
if(isset($_POST)){
$step = $_REQUEST['step'];
$url = $_REQUEST['url'];
$pass_fail = $_REQUEST['pass_fail'];
$comment = $_REQUEST['comment'];
$sql1 ="UPDATE qa_testing_application SET step='".implode(',',$step)."',url='" . implode(',',$url) . "',pass_fail='" . implode(',',$pass_fail) . "',comment='" . implode(',',$comment) . "' WHERE test_case_name='$test_case_name'";
$result= mysqli_query($database, $sql1) or die(mysqli_error($database));
}
?>
I am inserting it this way. And i would like to retrieve it from the DB.
I would love to display it as follows:
Please see the link http://i.stack.imgur.com/6aglk.jpg
At the moment i am trying to test and figure out how to display it:
Not sure how to implement a for or foreach function in here as well if thats needed.
$countsteps = 0;
$counturls = 0;
$countpass_fails = 0;
$countcomments = 0;
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
while($fetch=mysqli_fetch_object($result))
{
$step=$fetch->step;
$url=$fetch->url;
$pass_fail=$fetch->pass_fail;
$comment=$fetch->comment;
$steps=explode(",",$step);
$urls=explode(",",$url);
$pass_fails=explode(",",$pass_fail);
$comments=explode(",",$comment);
echo '<td>'.$steps[$countsteps++].'</td>';
echo '<td>'.$urls[$counturls++]."</td>";
echo '<td>'.$pass_fails[$countpass_fails++]."</td>";
echo '<td>'.$comments[$countcomments++]."</td>";
}
So how would I get this to display in a table?
edit:
Oh and this is the error that I get:
Undefined Offset
This error simply says there is no such key exists into given array or you're trying to fetch a value from non-array variable.
To show data into tabular format, you don't need to explode data coming from db. They are already concatenated.
So to show data from db, modify your code as show below:
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
echo '<table>';
echo '<th>Step</th><th>Url</th><th>Pass/Fail</th><th>Comment</th>';
while($fetch=mysqli_fetch_object($result))
{
echo '<tr>';
echo '<td>'.$fetch->step.'</td>';
echo '<td>'.$fetch->url.'</td>';
echo '<td>'.$fetch->pass_fail.'</td>';
echo '<td>'.$fetch->comment.'</td>';
echo '</tr>';
}
echo '</table>';
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 :)