Struggling to output PHP array as unordered HTML list - php

Apologies as this is probably very basic. I have created a SELECT query and have (I think) stored the data retrieved as an array.
By myself I have been able to use printf to output selected items from the array but I want to output the values in a more structured way, as an unordered list in HTML. It's going to be a list of links. anchor corresponds to the link name column in my MySQL table and link corresponds to the url column, to be output as, e.g
<li>anchor</li>
This is as far as I have got. I know I need a for loop but the demos I've copied keep failing.
Very grateful for any pointers from kind people. Backend is new to me.
<?php
$server = "localhost";
$username = "blah";
$password = "blahblah";
$database = "blah_db";
$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($conn, "SELECT anchor, link FROM footerLinks");
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
printf("Anchor: %s Link: %s ", $row[0], $row[1]);
}
mysqli_free_result($result);
?>

There is not much to change in your code. Add <ul> and </ul> around the while loop. Change the pattern to <li>%s</li>. And swap $row[0], $row[1] to $row[1], $row[0]:
$result = mysqli_query($conn, "SELECT anchor, link FROM footerLinks");
echo '<ul>';
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
printf('<li>%s</li>', $row[1], $row[0]);
}
echo '</ul>';
I would though use MYSQLI_ASSOC instead of MYSQLI_NUM (which is considered bad practice), and also use the object oriented style for mysqli functions:
$result = $conn->query("SELECT anchor, link FROM footerLinks");
echo '<ul>';
while ($row = $result->fetch_assoc()) {
printf('<li>%s</li>', $row['link'], $row['anchor']);
}
echo '</ul>';

Related

PHP get data from database and put the data into a string

I am still new to PHP. I have tried a few stuff, but I just can't get it to work.
Question: I want all the data from my users table to be in a string, separated by comma. Then when the ID is 2 to be ; for net new row, so on and so forth. If someone can please help me.
$server = "localhost";
$user_name = "root";
$password = "";
$database = "users";
$conn = new mysqli($server, $user_name, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Users;";
$result = $conn ->query($sql);
while($row = mysqli_fetch_array( $result )) {
$rows = implode (";",$result);
$array = $rows;
echo $array;
}
Question2: But if I want first row of DB data to be, separated and then at the end with a ;. How would I do that?
Output: The output of this code is:
Warning: implode(): Invalid arguments passed
You've simply used the wrong variable in your call to ìmplode.
You've assigned all the columns as an array to $row - but you're trying to implode $result.
Update that line to this:
$rows = implode(";", $row);
Let's say your user table has 2 fields Firstname and Lastname. What I understood from your question is you want your output to be something like
$array = ['steve,jobs;', 'mark,zukerberg;'];
To achieve this you can append ';' at the end of the string.
while($row = mysqli_fetch_array( $result )) {
$rows = implode(',',$row) . ';'; //you have named this variable $rows but it is going to have data of a single row
$array = $rows; //you could directly var_dump($rows) instead of assigning it to a new variable
echo $array; //you could rather use var_dump($array) for this
}

Populating array in PHP from MySQL table

I am newbie to PHP and need to seek your help on how to populate the array which is $dataArray[] with the rows of MySQL so that I will be able to call the data Array in some other function or say I want to print the $dataArray as above. I would be thankful to you if you can provide me example code modifications in my below code
<?php
$dataArray=array();
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT reg_date,xyz,pqr FROM stuvw";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$test = mysqli_num_rows($result);
echo $test;
while($row = mysqli_fetch_assoc($result))
{
$populate = '"' . $row["reg_date"]. '"'."=>" . $row["xyz"]. ", " ;
$dataArray[$populate] = $test;
}
echo $dataArray[$populate];
}
mysqli_close($conn);
?>
You can use an Associative array. This stores the data in a key-value format.
$dataArray[ $row['reg_date'] ] = $row['xyz'];
What you are doing in you example is creating a string in the $populate variable and using it as a key in the $dataArray. The number of rows returned from the SQL query is then stored as the value for each item in the $dataArray. This number is in the $test variable.
The key needs to be unique however so it makes sense to use the primary key from your MYSQL result as you key (if necessary).
Have a read through W3Schools PHP course.
http://www.w3schools.com/php/php_arrays.asp

MySQL/PHP - Getting differents rows

Alright, so I have a database, each with an ID, a name and a textvalue.
I wish to be able to print each of a specific row individually. When I use
$result = mysql_query("SELECT * FROM mytable", $db);
$row = mysql_fetch_array($result);
echo $row['text'];
I am only able to print the first row, as it doesn't select any specifics. The problem is, I'm not sure how to use the WHERE ID='X', as I want the first one to print the first column, the second to print the second column and so forth (there are a total of 13 lines). I want to echo them on different places on the page, so just calling everything at once is not what I'm looking for.
The way things are now, I'll have to use the code above for each time I want to print it, and manually edit the WHERE ID='1' on the first print, the second to WHERE ID='2' and so on, which is rather a pain in the ass.
Any suggestions is appreciated.
Keep calling mysql_fetch_array until it returns null:
while($row = mysql_fetch_array($result ))
{
echo $row['text'] . '<br/>';
}
This is shown in the documentation, which also will tell you this:
Warning
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. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
Here's an example using a more object-oriented approach:
1) setup a PDO object like this:
$dbhost = '127.0.0.1';
$dbuser = 'yourDbUsername';
$dbpass = 'yourDbPassword';
$dbname = 'databaseName';
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$dbAdapter = new PDO($dsn,$dbuser,$dbpass);
$dbAdapter->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbAdapter->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
2) use PDO objects to run queries and fetch result sets:
$sql = 'SELECT * FROM mytable';
$statementObject = $dbAdapter->query($sql);
$resultSet = $statementObject->fetchAll();
3) iterate over the resulting array:
foreach($resultSet as $row){
echo $row['text'] . "<br />";
}
This is how to iterate through all records.
$result = mysql_query("SELECT text FROM mytable", $db);
while ( $row = mysql_fetch_array($result) ) {
echo $row['text'];
}
$i = 1;
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $i . ' - ' . $row[0] . '<br/>';
$i++
}
If you want 4 variables with the text to use in differents part of your code then use:
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
$var1 = mysql_fetch_array($result, MYSQL_NUM);
echo $var1[0];
$var2 = mysql_fetch_array($result, MYSQL_NUM);
echo $var2[0];
$var3 = mysql_fetch_array($result, MYSQL_NUM);
echo $var3[0];
$var4 = mysql_fetch_array($result, MYSQL_NUM);
echo $var4[0];

Retrieving data from Mysql and storing in option html tag

Hey guys i'm stuck on this question. What I'm trying to do is retrieve some data from MYSQL and store it in an option tag. Here is my code.
<?php
$user = "admin";
$password = "";
$db = "test";
$host = "localhost";
$cxn = mysqli_connect($host, $user, $password, $db);
$query = "SELECT ARTIST FROM music";
$results = mysqli_query($cxn, $query) or die("Connection could not be established");
echo "<select name='mediaType'>";
while ($row = mysqli_fetch_assoc($results))
{
extract($row);
echo "<option value=''>$row</option>\n";
}
echo "</select>";
?>
After preforming this function the output in the option tag is "Array" for all options in the select element. I tried storing the data from the php variable $row into an array then looping threw that array and echoing out each index in the array, but the results were the same. May someone plz provide me some guidance on this issue. Thanks all who help.
Per the other users, extract() is not what you want here. $row is an array where the keys are your column names. Use something like this:
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="">'.$row['ARTIST'].'</option>';
}
Note how I changed the quotes; the array operator doesn't work within a double-quoted string.
And in the future, to inspect the contents of a variable, look into using var_dump(), it's great for seeing what's going on behind the scenes.
Edit: oh, and if your table has a numeric primary key ID, you should probably use that as the value for your select, to protect yourself against changing names or human-input typos.
Why not simply do:
echo "<select name='mediaType'>";
while ($row = mysqli_fetch_assoc($results))
{
echo "<option value='".$row['ARTIST']."'>".$row['ARTIST']."</option>";
}
echo "</select>";

How get all values in a column using PHP?

I've been searching for this everywhere, but still can't find a solution: How do I get all the values from a mySQL column and store them in an array?
For eg:
Table Name: Customers
Column names: ID, Name
# of rows: 5
I want to get an array of all the 5 names in this table. How do I go about doing that? I am using PHP, and I was trying to just:
SELECT names FROM Customers
and then use the
mysql_fetch_array
PHP function to store those values in an array.
Here is a simple way to do this using either PDO or mysqli
$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);
or, using mysqli
$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
$array[] = $row['column'];
}
print_r($array);
Array
(
[0] => 7960
[1] => 7972
[2] => 8028
[3] => 8082
[4] => 8233
)
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here :
http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
I would use a mysqli connection to connect to the database. Here is an example:
$connection = new mysqli("127.0.0.1", "username", "password", "database_name", 3306);
The next step is to select the information. In your case I would do:
$query = $connection->query("SELECT `names` FROM `Customers`;");
And finally we make an array from all these names by typing:
$array = Array();
while($result = $query->fetch_assoc()){
$array[] = $result['names'];
}
print_r($array);
So what I've done in this code:
I selected all names from the table using a mysql query. Next I use a while loop to check if the $query has a next value. If so the while loop continues and adds that value to the array '$array'. Else the loop stops. And finally I print the array using the 'print_r' method so you can see it all works. I hope this was helpful.
Since mysql_* are deprecated, so here is the solution using mysqli.
$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
die("Connection to MySQL-server failed!");
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
while($arr = $executingFetchQuery->fetch_assoc())
{
$resultArr[] = $arr['name'];//storing values into an array
}
}
print_r($resultArr);//print the rows returned by query, containing specified columns
There is another way to do this using PDO
$db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
//to fetch records
$fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
$fetchD->execute();//executing the query
$resultArr = array();//to store results
while($row = $fetchD->fetch())
{
$resultArr[] = $row['name'];
}
print_r($resultArr);
First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function
function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
$databaseConnectionQuery = mysqli_connect($serverName, $userName, $password, $databaseName);
if($databaseConnectionQuery === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
return false;
}
$resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
$fetchFields = mysqli_fetch_fields($resultQuery);
$fetchValues = mysqli_fetch_fields($resultQuery);
if (mysqli_num_rows($resultQuery) > 0)
{
echo "<table class='table'>";
echo "<tr>";
foreach ($fetchFields as $fetchedField)
{
echo "<td>";
echo "<b>" . $fetchedField->name . "<b></a>";
echo "</td>";
}
echo "</tr>";
while($totalRows = mysqli_fetch_array($resultQuery))
{
echo "<tr>";
for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
{
echo "<td>";
echo $totalRows[$eachRecord];
echo "</td>";
}
echo "<td><a href=''><button>Edit</button></a></td>";
echo "<td><a href=''><button>Delete</button></a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No Records Found in";
}
}
All set now Pass the arguments as For Example
$queryStatment = "SELECT * From USERS ";
$testing = displayAllRecords('localhost','root','root#123','email',$queryStatment);
echo $testing;
Here
localhost indicates Name of the host,
root indicates the username for database
root#123 indicates the password for the database
$queryStatment for generating Query
hope it helps
PHP 5 >= 5.5.0, PHP 7
Use array_column on the result array
$column = array_column($result, 'names');
How to put MySQL functions back into PHP 7
Step 1
First get the mysql extension source which was removed in March:
https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql
Step 2
Then edit your php.ini
Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:
extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/mysql.so
Step 3
Restart PHP and mysql_* functions should now be working again.
Step 4
Turn off all deprecated warnings including them from mysql_*:
error_reporting(E_ALL ^ E_DEPRECATED);
Now Below Code Help You :
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$Data[] = $row['names'];
}
You can also get all values in column using mysql_fetch_assoc
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_assoc($result))
{
$Data[] = $row['names'];
}
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Reference
YOU CAN USE MYSQLI ALTERNATIVE OF MYSQL EASY WAY
*
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>

Categories