Outputting a list of MySQL table values in PHP/HTML - php

I have a MySQL list with a few categories and a lot of rows of data. I want to simply output that in PHP/HTML. How would I do that?

<?php
$query = "SELECT * FROM TABLE";
$res = mysql_query($query,$connection);
while($row = mysql_fetch_array($res)) {
print_r($row);
}
?>

To expand on what was already said: http://www.anyexample.com/programming/php/php_mysql_example__display_table_as_html.xml
This will produce a nice html table out of a query.

Please note that the mysql_* functions, as offered by some answers to this question, have been deprecated for quite some time. It is recommended to use either the mysqli_* functions (MySql Improved, which uses a newer underlying library for accessing mysql), or the PDO (PHP Data Objects, an object-oriented interface for connecting to various databases).
For example:
// Create a new PDO connection to localhost.
$dbh = new PDO("mysql:localhost;dbname=testdb", $user, $password);
// Create a PDO Statement object based on a query.
// PDO::FETCH_ASSOC tells PDO to output the data as an associative array.
$stmt = $dbh->query("SELECT * FROM Table", PDO::FETCH_ASSOC);
// Iterate over the statement, using a simple foreach
foreach($stmt as $row) {
echo $row['column1'].' and '.$row['column2'];
}

Related

How to use total rows in mysql table for loop's counter in php? [duplicate]

What are some different ways to loop through a mysql result set? I'm new to PHP and MySQL so I'm looking for simple ways to loop through and an explanation as to how the provided code works.
the first example that comes to my mind:
<?php
$link = mysql_connect(/*arguments here*/);
$query = sprintf("select * from table");
$result = mysql_query($query, $link);
if ($result) {
while($row = mysql_fetch_array($result)) {
// do something with the $row
}
}
else {
echo mysql_error();
}
?>
Here is a full example:
http://php.net/manual/en/mysqli-result.fetch-array.php
Connect
Select database
Make query
Cycle on the result and fetch array to get the row
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT * FROM table";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
foreach ($result as $row):
?>
//Loop Content... Example:-
<li><?= $row['name']; ?></li>
<?php
endforeach;
?>
If you are using MySQL versions 4.1.3 or later, it is strongly recommended that you use the mysqli extension instead [of the mysql extension that is not further developed, does not support features of MySQL 4.1+, no prepared and multiple statements, has no object-oriented interface, ...]
see mysqli-stmt.fetch for the procedural and object oriented ways to loop over a mysqli result set.
In modern php, you don't need to call any functions to fetch the data of a result set. The result set object is immediately iterable and a foreach() will allow you to traverse the data as if it was an indexed array of associative arrays. (Since PHP5.4.0, circa March 1, 2012 - "MySQLi: Added iterator support in MySQLi. mysqli_result implements Traversable.")
Example:
foreach ($conn->query("SELECT one, two, three FROM my_table") as $index => $row) {
echo "<div>$index: {$row['one']}, {$row['two']}, {$row['three']}</div>";
}
I'd recommend creating a database function that acts as a wrapper for your database fetch. Makes it easier to switch out database function calls, and even, down the road, the type of database itself (e.g. mysql->postgresql or mysql->couchdb or using the PDO object or something).
Some function that -you- create that takes a query and returns a fully associative array, and then you stick the database connection code inside there.
It may also be good to check into using PDO down the road, since it abstracts away database specific functions for you, working with mysql, postgresql, etc.

Get only one Jsonobject reponse while there are two match data?

I wrote the PHP code below to get multiple JSON objects from my database:
<?php
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
$rowOfDate = $result->fetch_assoc();
echo json_encode($rowOfDate);
I expect to get two JSON objects when I run the PHP file like below because I have two month 11 data matching in My MySQL:
[{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"},{"account":"Fu","ssid":"Fu","date":"2019-11-21 00:00:00"}]
But I only get one JSON object like below:
{"account":"Fu","ssid":"Fu","date":"2019-11-14 00:00:00"}
How to solve the problem?
You need to fetch each row in your result. You're only calling fetch_assoc() once in your code. You need to either loop until fetch_assoc() returns false, or use fetch_all() (which is supported only by the mysqlnd driver.)
$connection = new mysqli("localhost","root","","Fubon");
$dateCheckSQLCommand = $connection->prepare("select * from clockindata where Month(date)= 11 ");
$dateCheckSQLCommand -> execute();
$result = $dateCheckSQLCommand->get_result();
/*** either this ****/
while($row = $result->fetch_assoc()) {
$rowOfDate[] = $row;
}
/*** or this, if it's supported ***/
$rowOfDate = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($rowOfDate);
The best solution, though, will involve changing the database API you're using. Mysqli is not very user friendly, and was written as a low-level one-to-one mapping of MySQL's C API. Even using PDO, which is PHP's other built-in database API, will make your code much easier to work with. Here's how that would look, including a parameterized query for safety:
$month = 11;
$db = new PDO("mysql:host=localhost;dbname=Fubon", "root", "of course you have a password");
$stmt = $db->prepare("SELECT * FROM clockindata WHERE MONTH(`date`) = ?");
$stmt->execute([$month]);
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// if your script is outputting JSON, set the MIME type appropriately
header("Content-Type: application/json");
echo json_encode($data);
Especially when you're using parameters in your query (which you already are, of course, right?) PDO becomes far easier to use than Mysqli.

PHP Fetchall only returning column header

I have a database that I am trying to query to get information to display to my user. I have used
fetch(PDO::FETCH_ASSOC)
before when retrieving a single row or
$row = mysql_fetch_array($result)
with good results. However, it is my understanding that it is better practice to use PDO so that is what I am trying to do.
The problem I am running into is that my results are only showing me the first row of the data I need. In this instance it is displaying the column header over and over and never giving me the data.
$stmt = $conn->prepare("SELECT ? FROM application");
$stmt->bindparam(1, $application_ID);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
}
Here are the results
application_IDapplication_IDapplication_IDapplication_ID
It is good that you are aware that MySQL has been oficially deprecated and now we are supposed to used MySQLi or better yet, PDO.
Since you are not accepting any user input, there is no need of using a prepared statement.
Simply do this:
$stmt = $conn->query("SELECT * FROM application");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row){
echo $row['application_ID'];
//output other rows here
}
As per the php documentation pdo::fetchAll
you have to use fetchAll, instead of fetchall.

Do unbuffered queries for one request

I'm looking to do unbuffered queries only on some requests.
In MySQL I was doing this:
$req = mysql_unbuffered_query('SELECT * FROM forum_topics
ORDER BY (topic_id/topic_stick) DESC, topic_last_post DESC');
while($data = mysql_fetch_assoc($req)) {
// display results...
}
I looked at PHP doc, and according to it in pdo we must proceed this way to do queries unbuffered:
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$uresult = $pdo->query("SELECT Name FROM City");
if ($uresult) {
while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
echo $row['Name'] . PHP_EOL;
}
}
But is it possible to do it unbuffered only for the "forum_topics" table results without setting all pdo instance to unbuffered?
Re, this doesn't work, I obtain an error while using your method:
SQLSTATE[IM001]: Driver does not support this function: This driver doesn't support setting attributes
What's wrong?
Edit : I found the solution on php.net doc.
If you use this:
$sth->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
It doesn't work.
But if you set it in an array in prepare(), it works fine.
$sth = $pdo->prepare('SELECT * FROM my_table',
array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false));
I hope this will help people who haven't found a way for this problem.
You can set the attribute on the PDO connection:
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
then run this particular query which result needs to be unbuffered,
$uresult = $pdo->query("SELECT Name FROM City");
while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
echo $row['Name'] . PHP_EOL;
}
and then set the attribute back
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
The answers on here are all trying to use MYSQL_ATTR_USE_BUFFERED_QUERY on the statment. and MYSQL_ATTR_USE_BUFFERED_QUERY only operates on the entire connection, as you seem to have sussed out.
MYSQL_ATTR_USE_BUFFERED_QUERY also only works if you're using the mysqlnd library - which odds are good you are if you're using PHP 7 or higher.
Your original method of setting the connection as unbuffered was the correct and only actually functional method.
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
But is it possible to do it unbuffered only for the "forum_topics" table results without setting all pdo instance to unbuffered?
Not all instances are set to unbuffered, only that "instance" of that connection. You can either simply immediately turn buffering back on ala:
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
The problem is that you can only iterate a single query per connection when in unbuffered mode, so you cannot run a second query until you have retrieved all data from the first set.
Normally you only want to use unbuffered queries for very large datasets. I would recommend to use a second PDO connection to the database specifically for unbuffered queries that you open only when you need to run an unbuffered query, aka:
$pdo2 = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo2->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
MySQL does not implement statement-level attribute setting.
Source:
Here is your error message:
https://github.com/php/php-src/blob/master/ext/pdo/pdo_stmt.c#L1630
pdo_raise_impl_error(stmt->dbh, stmt, "IM001", "This driver doesn't support setting attributes");
And the condition above is checked on the stmt->methods->set_attribute above.
The stmt->methods is defined above and the type is declared at:
https://github.com/php/php-src/blob/5d6e923d46a89fe9cd8fb6c3a6da675aa67197b4/ext/pdo/php_pdo_driver.h#L417
struct pdo_stmt_methods
The set_attribute parameter is the 10th struct entry.
Here is the MySQL PDO implementation. And the statements methods are defined here:
https://github.com/php/php-src/blob/2ba4fb126391c578d20d859c841c4d31cd14adef/ext/pdo_mysql/mysql_statement.c#L935
NULL, /* set_attr */
This shows that the MySQL PDO module does implement that feature.
Discussion:
I have reviewed other extensions. And only the Firebird PDO database module supports that feature.
As an workaround if my query is a SELECT, I don't call the fetchAll function.
$query = 'SELECT ...... ';
$arr = explode(' ', $query);
$query_type = strtolower($arr[0]);
if ($query_type == 'select') {
$query_response = $query_prepare->fetchAll(PDO::FETCH_ASSOC);
} else {
$query_response = '';
}
Also you must treat the exception when you accidentaly put a space at the begining of the query.
Hope this is helpful.

PHP delete values from mysql bad

I have a script which works without errors, but can't delete chosen value from mysql.
It looks like: What problem could be?
include('opendb.php');
$a = $_GET['new_pav'];
$select = mysql_query("SELECT * from naujiena WHERE new_pav = '$a'");
while($row = mysql_fetch_row($select)){
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");
}
Firstly, read this (and below):
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
The red warning box is telling you to stop using mysql_* in anything new.
As for your query, DELETE FROM x WHERE y=z is a valid query, so the error could be from your use of quotes (if new_pav is an int, then this could explain it); strings are quoted in MySQL.
Also, do not interpolate/concat strings in an SQL query, or you risk SQL Injection. Look up pdo, and start using classes for something that involves a state (the db connection), rather than a variable and countless functions. (I originally used mysqli here):
try {
$db = new PDO("mysql:dbname=$dbname;host=$dbhost", $dbuser, $dbpass);
$query = $db->prepare("SELECT COUNT(*) FROM naujiena WHERE new_pav = :pav");
if (!$query->bindParam(":pav", $_POST["new_pav"])) {
die("Input incorrect; couldn't bind");
}
$query->execute();
$rows = $query->fetchColumn(0); // fetch a single column. count(*) here.
if ($rows !== 0) { // It has a result~
$query = $db->prepare("DELETE FROM naujiena WHERE new_pav = :pav");
$query->execute(array(":pav" => $_POST["new_pav"]));
}
$db = null; // explicitly close connection
} catch (PDOException $e) { // catch any exception PDO throws at you.
// note that you should catch where appropriate.
die("Connection Failed: " . $e->getMessage());
}
Note that with SQL Injection, I could type ' OR 1=1 -- and delete your whole table.
As you can see, this is far from a one/two-liner, but you must never trust anything added to SQL that you didn't hardcode in yourself, period.
Apart from using mysql_ libraries your code:
$select = mysql_query("SELECT * from naujiena WHERE new_pav = '$a'");
while($row = mysql_fetch_row($select)){
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");
}
In the SELECT you are not escaping the value of $a but in the delete you are escaping it.
Anyway if you are just doing a delete you do not need the SELECT or while loop. So you could use the following code:
$result = mysql_query("DELETE FROM `naujiena` WHERE new_pav='".mysql_real_escape_string($a)."' ");

Categories