Populating array in PHP from MySQL table - php

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

Related

Why does echo $row[1] work but not echo $row[2]?

I have a MySQL database and am trying to print out the contents of specific rows. For some reason echo $row[1]; prints out the contents of row 1 perfectly, but I'm unable to do the same for the other rows (echo $row[2];, echo $row[3];, etc). The table has a unique index column with four rows labeled 1-4.
What I'd eventually like to do is print out just the contents of the last row, which I thought would look something like echo $row['$maxrows']; however I can't even get the syntax for printing any row past 1!
I think that this may be an issue with my table, but can't quite see what it is as there is an index column. Any suggestions or pointers would be appreciated?
What might I do to echo rows in my table past row 1?
UPDATE
var_dump($row); returns the below
{ [0]=> string(1) "1" ["Index"]=> string(1) "1" [1]=> string(121) "https://www.tilley.com/media/catalog/product/cache/image/1100x1100/e9c3970ab036de70892d86c6d221abfe/t/t/ttw2_black2_a.jpg" ["Sketch"]=> string(121) "https://www.tilley.com/media/catalog/product/cache/image/1100x1100/e9c3970ab036de70892d86c6d221abfe/t/t/ttw2_black2_a.jpg" }
The table has two columns:
1-Name: Index - int(11) - AUTO_INCREMENT
2-Name: Sketch - text
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Table";
$result = mysqli_query($conn, $sql);
$maxrows = mysqli_num_rows($result);
//$result = $conn->query("SELECT * FROM Table");
$row = $result->fetch_array(MYSQL_BOTH);
echo $maxrows;
echo $row[1];
echo $row[2];
echo $row[3];
echo $row[4];
//echo $result;
$conn->close();
Your result array has 4 keys: 0, Index, 1 and Sketch, that's the results of the first row only. You're querying 2 columns but try to access 4 columns. Column numbering starts with 0. And you're not iterating the result rows. That $row = $result->fetch_array(MYSQL_BOTH); should be in a loop.
Turn on error reporting. PHP would show you which undefined variables your accessing.
Use PDO in favor to mysqli.
Don't create an array with both column name indexes and numeric indexes (don't use MYSQL_BOTH). Use PDO::FETCH_ASSOC or PDO::FETCH_NUM.
Start using var_dump() instead of echo for debugging. Always.
Use a foreach loop when processing the result array.

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
}

Looping array to update mysql table

Is it possible to construct a loop which takes every single value from an array and then updates a mysql table?
What the array looks like
output
Team Blue
4
4
Team Red
4
4
Bare in mind that the 4's are Id's.
Array code
$players = $lista;
shuffle($players);
$player_count = count($players);
$players_per_team = $player_count/2;
$teams = array_chunk($players,$players_per_team);
$team_1 = $teams[0]; // Lag 1
$team_2 = $teams[1]; // Lag 2
echo "Team Blue";
echo "<br>";
foreach ($team_1 as $value) {
echo $value . "<br>";
}
echo "<br>";
echo "Team Red";
echo "<br>";
foreach ($team_2 as $value) {
echo $value . "<br>";
}
How can i select each element in the array?
Basically all i need to do is to update a single column for each id in both arrays.
See picture
https://gyazo.com/ceb49db66ba85b9a6adfa0daf30c7a57
I want to update "team" column.
My guess is that i need to make some sort of loop, but i have no clue on how to select each element and then querying it.
So my question is.
How can i select each element in the array and loop some sort of query to update a single column?
If i need to provide more information, just tell me!
Thank you for taking your time reading my question, kind regards Jonas
Google is your friend:
"php mysqli update column"
Best Result: https://www.w3schools.com/php/php_mysql_update.asp
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Before you update or insert data check if your value are a integer
if (is_numeric($myArr[0])) {
// number
} else {
// something other
}

JSON - No repeating table name

I have some problems with json..
I will let my code here, and i will show you what does it print to me, and what i need to be printed..
Well... this is my code:
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","3d") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$query = "SELECT team FROM hs";
$result = mysqli_query($connection, $query) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$arr = array();
while($row =mysqli_fetch_assoc($result))
{
$arr[] = $row;
}
echo json_encode($arr);
//close the db connection
mysqli_close($connection);
And it print me a json code, like:
[{"team":"coco"},{"team":"dada"},{"team":"fafa"},{"team":"momo"}]
My question is, how can i print a json code like this:
{"team":[["coco"],["dodo"]...]}
Another question is, how can i print a json code like this: (I want to group 2 teams, like a power of 2...
{"team":[["coco","dada"],["fafa","momo"]]}
Thank you, and have a nice day...
You need to form a proper array in your php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","3d") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$query = "SELECT team FROM hs";
$result = mysqli_query($connection, $query) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$arr = $new_arr = array();
while($row =mysqli_fetch_assoc($result))
{
$arr[] = $row['team'];
}
shuffle($arr);
$new_arr['team'] = array_chunk($arr, 2);
echo json_encode($new_arr);
//close the db connection
mysqli_close($connection);
The thing that is getting printed is a json array which consists of JSON objects hence you see the result like:
[{"team":"coco"},{"team":"dada"},{"team":"fafa"},{"team":"momo"}]
What I would suggest is, you should create a json array and keep adding json objects to it.
JSONArray team = new JSONArray();
team.add("coco");
team.add("dodo");
and so on.
Coming to your second doubt, create json arrays which will contain pairs of elements such as coco and dodo in one, foo and bar in other. Let's call these arrays arr1 and arr2.
Now create the main JSON array named team and do the following:
team.put(arr1);
team.put(arr2);
And you'll see the result you want. Do ask for clarifications if any. :)

PHP: Retrieving two most recent mySQL table entries and storing each in a different variable

Please see the below code.
I am trying to retrieve the most recent two "element_value"s from my database table and then put them into a different table, with one column each. I can do this part with a mysql insert statement if I can get them into variables within the PHP, at the moment I have them being echoed out to the screen instead.
Does anyone know please how I can get them into two separate variables instead?
Thanks!
//Connect to database
$con=mysqli_connect("localhost","user","pass","dbname");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL database: " . mysqli_connect_error();
}
//Query the database
$result = mysqli_query($con, 'SELECT element_value FROM wp_formmaker_submits ORDER BY id DESC LIMIT 2;');
//Process the results
if (mysqli_num_rows($result) > 0) {
while ( $dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
}
Change :
while ($dataValue = mysqli_fetch_row($result))
echo "<p>".$dataValue[0]."</p>";
To this :
$values = null;
while ($dataValue = mysqli_fetch_assoc($result))
{
$values[] = $dataValue['element_value'];
}
print_r($values);
This will store your values in an array, I've added print_r at the end just so you can see the resulting data structure.
If you want to display them in an array again, you can do this :
foreach ($values as $value)
{
echo "<p>".$value."</p>";
}
I've changed your fetch_row method for fetch_assoc, an explanation can be found here : https://stackoverflow.com/a/9540590/2483649

Categories