Trying to get results to show on table with PDO Statement - php

I am new to PDO trying to figure how to get this to work with PDO. I have it working with MYSQL I maybe confused how PDO works. I am getting a blank page any ideas on how I can go about getting all the results of received records. I see tutorials on PDO but when I do it it is for single records with an array.
<?php
require_once("../db_connect.php");
$stmt = $db->prepare ("SELECT * FROM requests WHERE status='Received'");
echo"Received Requests";
echo "<br><br>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo("<table bgcolor=F2F2F2 width=1080 border='2'>");
echo("<br><tr><th>Id</th><th>Update</th><th>LanID</th><th>Name</th><th>Location</th><th>Manager</th><th>request</th><th>Description</th><th>request_comments</th><th>Status</th><th>Comments</th><th>Completed User</th><th>Completed Date</th></tr>");
echo("<tr>");
echo "<td>". $row['id'] . "</td>"
."<td><a href='../update.php?id=" . $row['id'] . "'>Update</a></td>"
."<td>" . $row['lanId'] . "</td> "
. "<td>". $row['name'] . "</td>"
. "<td>". $row['department'] . "</td>"
. "<td>" . $row['manager'] . "</td>"
. "<td>" . $row['request'] ."</td>"
. "<td>" . $row['request_description'] ."</td>"
. "<td>" . $row['request_comments'] ."</td>"
. "<td>" . $row['status'] ."</td>"
. "<td>" . $row['comments'] ."</td>"
. "<td>" . $row['compUser'] ."</td>"
. "<td>" . $row['compDt'] ."</td>";
echo '</tr>';
}
echo("</table>");
?>
<html>
<head>
<meta http-equiv="refresh" content="5" >
<title>
</title>
</head>
<body background="../images/background.jpg">
</body>
</html>
db_connect.php
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "systems_requests";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
?>

You forgot to execute your prepared statement.
Please use $stmt->execute () before using $stmt->fetch ()
Also please fetch like so:
$requests = $stmt->fetch (PDO::FETCH_ASSOC);
foreach ($requests as $request) {
echo $request["whateverKeyYouWant"];
}

Related

Get data from SQL database of multiple columns stored in explode function using PHP

I am using this code to get that data from SQL Server database using PHP
<?php
foreach ($dbDB->query($query) as $row) {
echo "<tr>";
echo "<td>" . $row['Country'] . "</td>";
echo "<td>" . $row['OrderNumber'] . "</td>";
echo "<td>" . $row['Region'] . "</td>";
echo "<td>" . $row['ShipDate'] . "</td>";
echo "<td>" . $row['ProducedDate'] . "</td>";
echo "</tr>"; }
?>
I am trying to replace these multiple lines but storing the columns' names in a string for example $_POST['SelectedColumns'].
The values coming into post as comma separated string, For example : Country,OrderNumber,Region,ShipDate,ProducedDate
I have tried this solution but still not working for me.
<?php
$ser="********";
$db="******";
$user="******";
$pass="******";
$query = 'SELECT '.$_POST['SelectedColumns'].' FROM reporting.REPORT_ALL';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=*******;Database=******;Port=1456", $user, $pass);
$row = $_POST["SelectedColumns"];
$rows = explode(",",$row);
/*Here I have the another html code independent of this part */
foreach ($dbDB->query($query) as $dataRow) {
echo "<table>";
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
echo "</table>"; }
?>
Any suggestions please ?

MongoDB Collection data to Php table issue

I have php code for displaying MongoDB collection data to php tablle, when i run it it doesn't show any output,
please be kind enough to sort this
Here my code
<?php
$m = new MongoClient();
$db = $m->selectDB('MapData');
$collection = new MongoCollection($db,'ETom4');
$cursor = $collection->find();
//echo "<html><head><body>";
echo "<table>";
foreach($cursor as $doc) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Marks'] . "</td>";
echo "<td>" . $row['value'] . "</td>";
echo "</tr>";
}
echo "<table>";
//echo "</html></head></body>";
?>
You're using as $doc instead of as $row here.
foreach($cursor as $doc) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Marks'] . "</td>";
echo "<td>" . $row['value'] . "</td>";
Change it to the variable you need to use, being $doc and not $row:
$m = new MongoClient();
$db = $m->selectDB('MapData');
$collection = new MongoCollection($db,'ETom4');
$cursor = $collection->find();
//echo "<html><head><body>";
echo "<table>";
foreach($cursor as $doc) {
echo "<tr>";
echo "<td>" . $doc['Name'] . "</td>";
echo "<td>" . $doc['Marks'] . "</td>";
echo "<td>" . $doc['value'] . "</td>";
echo "</tr>";
}
echo "<table>";
//echo "</html></head></body>";
HTML stickler:
You also commented out 2 lines which you're including your markup inside <head></head> and have placed </html> before </body>.
$m = new MongoClient();
$db = $m->selectDB('MapData');
$collection = new MongoCollection($db,'ETom4');
$cursor = $collection->find();
//echo "<html><head></head><body>";
echo "<table>";
foreach($cursor as $doc) {
echo "<tr>";
echo "<td>" . $doc['Name'] . "</td>";
echo "<td>" . $doc['Marks'] . "</td>";
echo "<td>" . $doc['value'] . "</td>";
echo "</tr>";
}
echo "<table>";
//echo "</body></html>";
The syntax/structure is:
<html>
<head>
...
</head>
<body>
...
</body>
</html>
You can also add <!DOCTYPE html> as the first line.
(Modern-day) Web browsers require a valid doc type.
Consult: https://www.w3.org/QA/2002/04/valid-dtd-list.html
Footnotes:
You also need to make sure of the columns' letter-case.
They are case-sensitive when iterating over rows in a loop.
Therefore Name and name would be considered different.
If (any or all of) the above still doesn't work for you, then you may have errors somewhere.
So, check for errors.

Delete specific row in database table and generatet html table

This is my delete page :
<?php
require('includes/config.php');
$id = $_GET['ID'];
$pdoConnect = new PDO($db);
$query='DELETE * FROM studentraspored WHERE ID = "' . $id . '" ';
$pdoResult = $db->prepare($query);
$pdoExec = $pdoResult->execute($query);
header('location:index.php');
?>
This is generated table in my “memberpage.php”:
if (count($rows)){
foreach ($rows as $row) {
$_SESSION['row'] = $rows;
$id = floatval($row['ID']);
echo "<tr>" .
'<form action="delete_raspored.php" method="post">'.
"<td>" . $row["ID"] . "</td>" .
"<td>" . $row["den"] . "</td>" .
"<td>" . $row["chas"] . "</td>" .
"<td>" . $row["predmet"] . "</td>" .
"<td>" . $row["profesor"] . "</td>" .
"<td>" . $row["prostorija"] . "</td>" .
"<td>" . $row["tip"] . "</td>" .
'<td><input type="submit" id="' . $id . '" value="Delete" ></td>'.
"</form>".
"</tr>"
This not working properly. I don't understand why maybe something i missed with floatval
Start by trying this:
<?php
require('includes/config.php');
$id = $_GET['ID'];
$query='DELETE FROM studentraspored WHERE ID = ?';
$pdoResult = $db->prepare($query);
$pdoResult->execute(array($id));
header('location:index.php');
exit();
Note the placeholder in place of the actual value, this will prevent SQL injections. The value is passed in in the execute, or you could bind it (http://php.net/manual/en/pdostatement.bindparam.php). http://php.net/manual/en/pdo.prepared-statements.php
The delete syntax was also off, delete deletes a whole row not specific columns, http://dev.mysql.com/doc/refman/5.7/en/delete.html.
In your form I also don't see an element named ID so that could be another issue and your form is submitting via POST, not GET.

Run Query in PHP to display in table

I'm trying to create a league table, the query works in phpmyadmin. But I cannot display it in a table using php.
I think the issue is that I'm not running the query the correct way. When I run the code I get "league table query not populated"
Please can you give some advice on running this:
<?php
$sql =
"SELECT player_name,
SUM(win+draw+lose) AS Played,
SUM(win) AS Won,
SUM(draw) AS Drawn,
SUM(lose) AS Lost,
SUM(`for`) AS `Goals For`,
SUM(`against`) AS `Goals Against`,
SUM(cast(`for`AS SIGNED) - cast(`against`AS SIGNED)) AS `Goal Difference`,
SUM((win*3)+(draw)+extra_points) AS Points,
ROUND((SUM((win*3)+draw))/SUM((win+draw+lose)*3)*100,1) AS Record
FROM appearances
WHERE season_id = 4
GROUP BY player_name
ORDER BY Points DESC,
Played ASC,
`Goal Difference` DESC, `Goals For` DESC,
player_name ASC[...]";
if (!$sql) {
echo 'sql query has not worked';
}else {
$leaguetable = mysql_query($sql);
if (!$leaguetable){
echo 'league table query not populated';
} else {
$records = mysql_fetch_array($leaguetable);
If (!$records) {
echo 'records have not been placed in assoc array';
}
else {
echo "<tr width='600'>";
echo "<td>" . $records["player_name"] . "</td>";
echo "<td>" . $records["Played"] . "</td>";
echo "<td>" . $records["Won"] . "</td>";
echo "<td>" . $records["Drawn"] . "</td>";
echo "<td>" . $records["Lost"] . "</td>";
echo "<td>" . $records["Goals For"] . "</td>";
echo "<td>" . $records["Goals Against"] . "</td>";
echo "<td>" . $records["Goal Difference"] . "</td>";
echo "<td>" . $records["Points"] . "</td>";
echo "<td>" . $records["Record"] . "</td>";
echo "</tr>";
//while ($records = mysql_fetch_assoc($sql));
}
}
}
?>
When I run the above I get "league table query not populated"
Thanks in advance for your help
I've just tried the PDO method and its still not displaying the records, i believe there is a database connection, here's the code
<?php
require 'pdoconnect.php';
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$stmt = $db->prepare("SELECT player_name,
SUM(win+draw+lose) AS Played,
SUM(win) AS Won,
SUM(draw) AS Drawn,
SUM(lose) AS Lost,
SUM(`for`) AS `Goals For`,
SUM(`against`) AS `Goals Against`,
SUM(cast(`for`AS SIGNED) - cast(`against`AS SIGNED)) AS `Goal Difference`,
SUM((win*3)+(draw)+extra_points) AS Points,
ROUND((SUM((win*3)+draw))/SUM((win+draw+lose)*3)*100,1) AS Record
FROM appearances
WHERE season_id = 4
GROUP BY player_name
ORDER BY Points DESC,
Played ASC,
`Goal Difference` DESC, `Goals For` DESC,
player_name ASC[...]");
$stmt->execute();
$result = $stmt->fetchAll(pdo::FETCH_ASSOC);
while($row = $result){
echo "<tr width='600'>";
echo "<td>" . $row['player_name'] . "</td>";
echo "<td>" . $row['Played'] . "</td>";
echo "<td>" . $row['Won'] . "</td>";
echo "<td>" . $row['Drawn'] . "</td>";
echo "<td>" . $row['Lost'] . "</td>";
echo "<td>" . $row['Goals For'] . "</td>";
echo "<td>" . $row['Goals Against'] . "</td>";
echo "<td>" . $row['Goal Difference'] . "</td>";
echo "<td>" . $row['Points'] . "</td>";
echo "<td>" . $row['Record'] . "</td>";
echo "</tr>";
//while ($records = mysql_fetch_assoc($sql));
}
?>
Please replace this statement
$leaguetable = mysql_query($sql);
with
$leaguetable = mysql_query($sql) or die(mysql_error());
to check the reason due to which query failed
Not a real andwer and I don't know which version of PHP you are using but you might consider the warning on http://php.net/manual/en/function.mysql-query.php
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
you can do somting like this..
<!doctype html>
<html>
<head></head>
<body>
<table>
<tr>
<?php
header('Content-Type: text/html; charset=UTF-8');
mysql_connect("localhost", "user", "password");
mysql_select_db("alarm");
mysql_query( "SET NAMES utf8" );
mysql_query( "SET CHARACTER SET utf8" );
$dave = mysql_query("select blablabla as ab");
while ($row = mysql_fetch_assoc($dave)) {
echo $row['ab'];
echo "<td>";
.
. put where you want..
.
echo "<tr>";
}
?>
</body>
</html>
You have to connect to your database before issuing any query to it:
Try this on the beginning of your script (replace localhost, mysql_user and mysql_password with your servers data):
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_link= mysql_select_db('database_name', $link);
if (!$db_link) {
die ('Can\'t use database_name: ' . mysql_error());
}
See http://php.net/manual/en/function.mysql-connect.php
And http://php.net/manual/en/function.mysql-select-db.php for more detail.

PHP - SQL select Data display

<html>
<head>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8" />
<title>Using file functions PHP</title>
</head>
<body>
<h1>Web Development - Lab05</h1>
<?php
require_once("settings.php");
$dbconnect = #mysqli_connect($host, $user, $pswd, $dbnm);
if($dbconnect->connect_errno >0)
{
die('Unable to connecto to database [' . $db->connect_error . ']');
}
$queryResult = "SELECT car_id, make, model, price FROM cars";
echo "<table width='100%' border='1'>";
echo "<tr><th>ID</th><th>Make</th><th>Model</th><th>Price</th></tr>";
//initiate array
$displayrow= mysqli_fetch_array($queryResult);
//initiate while loop to iterate through table
while($displayrow)
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Make'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($dbconnect);
?>
</body>
</html>
This is doing my head in, I cannot figure out why it will not display the actual data apart from the Table header. No matter what I used.
I have tried mysqli_fetch_array, mysqli_fetch_row, mysqli_fetch_assoc but nothing works.
Help and explanation why it was not displaying the data would be much appreciated :)
First: You aren't running a query, you are only putting the query text in a variable. You need to use mysqli_query.
Second: You should add mysqli_fetch_array to the loop.
For example:
while($displayrow = mysqli_fetch_array($queryResult))
{
}
Otherwise you are only getting the first row.
Third: Array keys are case sensitive. There is no $row['ID'], as Jeribo pointed out, it is $row['car_id'] as referenced in your query. $row['Make'] is not the same as $row['make'].
Please Precision to names of field in Query ( car_id,make,...)
while($displayrow= mysql_fetch_assoc($queryResult) )
{
echo "<tr>";
echo "<td>" . $displayrow['car_id'] . "</td>";
echo "<td>" . $displayrow['make'] . "</td>";
echo "<td>" . $displayrow['model'] . "</td>";
echo "<td>" . $displayrow['price'] . "</td>";
echo "</tr>";
}
If you want to query outside you still have to set it in the loop:
$result = $db->query($queryResult)
while($row = $result ->fetch_assoc()){
...
}
a Good Tutorial is shown here: http://codular.com/php-mysqli
$row needs to be initialized so why don't you try:
while($row = mysqli_fetch_array($queryResult))
{
....
}
You have to get the result set first and then try fetching array from result set
<?php
require_once("settings.php");
$dbconnect = #mysqli_connect($host, $user, $pswd, $dbnm);
if($dbconnect->connect_errno >0)
{
die('Unable to connecto to database [' . $db->connect_error . ']');
}
$query = "SELECT car_id, make, model, price FROM cars";
$resultSet=mysqli_query($dbconnect,$query)
echo "<table width='100%' border='1'>";
echo "<tr><th>ID</th><th>Make</th><th>Model</th><th>Price</th></tr>";
//initiate array
$displayrow= mysqli_fetch_array( $resultSet);
//initiate while loop to iterate through table
while($displayrow)
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['Make'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['Price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($dbconnect);
?>
http://www.w3schools.com/php/func_mysqli_fetch_array.asp

Categories