Loop through mysql registries and printing them [duplicate] - php

This question already has answers here:
Looping through mysql database
(3 answers)
Closed 8 years ago.
I have a mysql database with some tables, I did a php script that will print a table like this:
[user name]
[field 1][field 2][field 3]
[value 1][value 1][value 1]
...etc, containing "n" values from each field corresponding to the user name.
but what I want is to display this table for each user, a loop printing this table for every user in my database. I know I will have to do a loop before the tag right? but I don't know which conditions this loop will have,someone could help me showing me how to do this?

You can try something like this. Note that You'll have to add database connection information and change database and table names.
$db_name = 'database';
$table_name = 'table';
mysql_connect() or die("MySQL Error: ". mysql_error());
mysql_select_db($db_name) or die("MySQL Error: ". mysql_error());
$columns_q = mysql_query("SHOW COLUMNS FROM $table_name");
if(!$columns_q){
die("Error fetching columns $table_name: " . mysql_error());
}
echo '<table><tr>';
while($column = mysql_fetch_assoc($columns_q)){
echo '<td>' . $column['Field'] . '</td>';
}
echo '</tr>';
$fields_q = mysql_query("SELECT * FROM $table_name");
if(!$fields_q){
die("Error fetching fields $table_name: " . mysql_error());
}
while($fields = mysql_fetch_assoc($fields_q)){
echo '<tr>';
foreach ($fields as $key => $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
echo '</table>';

Related

Display the information from a SQLite Query in the browser

So, I'm trying to use PHP in order to query an sqlite database, I have no problem with the connection or with the query itself, however, I don't know what I could do in order to display the data in a clean way, or even put it inside an HTML table. The code I'm working with right now is:
<?PHP
$connection = new SQLite3('my_db.db');
if($connection){
echo "Connected\n";
}
$results = $connection->query('SELECT * FROM Meter1');
while($row=$results->fetchArray()){
var_dump($row);
}
?>
After you have done a $row = fetchArray() the variable $row is a array containing the data returned from your query in the form of an Array. If you add SQLITE3_ASSOC it will be an Associative Array where the keys are the names of the database columns.
So lets assume your table has the columns id, name, dob then this would be how you get to that column data
<?php
$connection = new SQLite3('my_db.db');
if($connection){
echo "Connected\n";
}
$results = $connection->query('SELECT * FROM Meter1');
while($row=$results->fetchArray(SQLITE3_ASSOC)){
echo 'id = ' . $row['id'] . '<br>';
echo 'name = ' . $row['name'] . '<br>';
echo 'Date of Birth = ' . $row['dob'] . '<br>';
}
?>
So if you want the data in a table its just a case of wrapping the HTML around that while loop like this
echo '<table>';
echo '<tr><td>id</td><td>name</td><td>Date of Birth</td></tr>';
while($row=$results->fetchArray(SQLITE3_ASSOC)){
echo '<tr>';
echo "<td>$row[id]</td><td>$row[name]</td><td>$row[dob]</td>";
echo '</tr>';
}
echo '</table>';

Make PHP array from numerical data in MySQL table and multiply it

Good day,
I'm a noob at PHP and MySQl. Looking to be pointed in the right direction.
I have a MySql table with 5 columns. Each column represents a specific set of data. All numerical.
I want to write PHP code which takes each value in a single column and puts it into an array that I can then modify.
I don't know how to get each column as a separate array. Should I get an array of all the rows and then do something extra to separate each of the 5 numbers in each row into 5 separate arrays?
**
require_once 'login.php';
echo $db;
$conn = mysqli_connect($hn,$un,$pw,$db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$query = "SELECT xox FROM tablex WHERE id = '1'";
$result = $conn->query($query);
if(!$result) die ("Database access failed: " . $conn->error);
$rows = mysqli_fetch_row($result);
while($rows){
echo $rows['index'];
}
echo $rows[0];
?>
$statement = **yourDatabaseConnection**->query('SELECT column1 FROM table');
$datas = $statement->fetch();
$datas will be an array of your column1 datas
Try reviewing the php documentation, here is a good place to start...php:mysql_fetch_row
Take a look at the example below, if is not what you looking for, please edit your question and provide the approach you are taking (your code) so that we have a better understanding where you are having issues.
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>

PHP / MySQL: How to reduce code to echo Select results (working code)

I am new to PHP and MySQL and hope you can help me with some tipps or comments on this.
I have a MySQL db with a table "Languages" from which I want to fetch all data and then echo it on my page with some HTML tags around it.
In the example below "ISO" is a language code and "$trans" the selected translation of the language names, e.g. English.
The output here is a list of (customized) checkboxes with a checkbox for each language.
So far I have the following which works as intended but since I am new to this I was wondering if I actually need the While loop here or if there is a shorter / better way to get the same - in the end I only need to echo the results of my Select.
My PHP:
// select data from db
$tbl = "Languages";
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM " . $tbl . " ORDER BY ISO ASC";
$result = $conn->query($sql);
// create array
while($arrLanguages = $result->fetch_assoc()){
$languages[] = array("ISO" => $arrLanguages["ISO"], "trans" => $arrLanguages[$lang]);
}
$conn->close();
// echo results with some HTML tags
$i = 1;
foreach($languages as $language){
echo "<input type='checkbox' class='checkSingle' id='language" . $i . "' name='language' value='" . $language['ISO'] . " - " . $language["trans"] . "' />";
echo "<label for='language" . $i . "'>" . $language['ISO'] . "</label>";
$i++;
}
Never do select * if you don't intend to use all of the fields in the table. It's a waste of bandwidth/cpu cycles to request fields that'll simply be thrown away later.
$sql = "SELECT ISO, trans ...";
... execute ...
while($arrLanguages = ...) {
$languages[] = $arrLanguages;
}
Since you only selected the two fields you really wanted, $arrLanguages will contain ONLY those fields, and you don't have type in the full-blown array creation. That was done automatically by the fetch_assoc() call.

Error when fetching SQL array [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I am extremely new to PHP and I'm frustrated by the error of this simple task. I want to import a table from an SQL database and show it in a HTML table. But I keep getting errors when trying to fetch the table column names.
The connection with the database is made though, I tested that.
The error is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Table' at line 1.
I found this example on w3schools which I edited by other examples on php.net
If anybody can help me with this, I'd appreciate it.
<?php
error_reporting(-1);
$con = mysqli_connect('localhost', 'user', 'pass');
mysqli_select_db($con, 'database') or die("Could not found" . mysqli_error($con));
$query = ("select * from Table");
$result = mysqli_query($con, $query) or die ( mysqli_error ($con) );
//Print table
echo "<table>";
echo "<tr>";
if($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
//Print headers
foreach($row as $key => $value ){
echo "<td>" . $key . "</td>";
}
echo "</tr>";
}
$result = mysqli_query($con, $query) or die (mysqli_error());
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr>";
while( list($key, $value) = each($row)){
//Print value
echo "<td>" . $value . "</td>";
}
echo "<td>" . $value . "<i class='fa fa-caret-up'></i><i class='fa fa-caret-down'></i></td>";
echo "</tr>";
}
echo "</table>";
?>
Table is a reserved keyword and you cant use it like this. If you want to fetch some data from a table named users or some like this then the query should be -
select * from users

List all table contents from generated list of table column names

I have got one piece of code which gives me a list of all the column names for a specific table. Can i use this list as my $row['VARIABLE'] instead of specifying every row?
The current output of the table names can be seen here this is the second paragraph of text, the first ones are my table names (USERS, ADMIN_LOGIN)
I am working on making a small script which will list all the table contents of a table but it is likely the table will change often so i want a script which can auto generate the table of contents without me having to manually re-enter it all as i have done in the second piece of code below?
Thanks guys
<?php
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
echo $table['name'] . '<br />';
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
echo "ID = ". $row['ID'] . "\n";
echo "USERNAME = ". $row['USERNAME'] ."\n";
echo "AGE = ". $row['AGE'] ."\n";
echo "LOCATION = ".$row['LOCATION'] ."\n\n";
echo "ANYTHING_ELSE = ". $row['ANYTHING_ELSE'] . "\n";
echo "EMAIL = ". $row['EMAIL'] ."\n";
echo "PROFILE_APPROVED = ". $row['PROFILE_APPROVED'] ."\n";
echo "NUMBER_OF_BATTLES = ".$row['NUMBER_OF_BATTLES'] ."\n\n";
echo "TOTAL_WINS = ".$row['TOTAL_WINS'] ."\n\n";
}
?>
Yes, you can use variables for the index values of an array. For example,
$row = array('col_name' => 'column value');
$index = 'col_name';
echo $row[$index]; // Equivalent to $row['col_name']. Prints "column value"
You should be able to accomplish what you want pretty easily using the above logic. Basically just store the column names from the first query into an array, then loop through that array to get the column names each time you print a row.
Give this a try:
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
foreach ($columns as $col)
echo $col . " = " . $row[$col] . "\n";
}
I use the following in order to get a list of columns names in the order they are defined in the table. I use it to populate an insert/select when preserving data.
sel columnname
from dbc.columns
where databasename='databasename'
and tablename='tablename'
order by columnid;

Categories