Putting MySQL data into an array - php

I've tried for a couple of days to get all of the data from a MySQL column and put it inside an array, formatted in the following way:
$aSpam= array
( '.info'=> 'i'
, 'anal'=> 'i'
, 'anus'=> 'i'
, 'arse'=> 'i'
)
I've managed to echo it out formatted properly as you can see here: http://www.yourgrumble.com/phpbbforum/getSpam.php
with the following PHP code:
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT `SpamWord` FROM spamWords";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0;
while($row = $result->fetch_assoc()) {
if($counter){
echo ", '" . $row["SpamWord"]. "'=> 'i'";
$counter++;
} else {
echo "'" . $row["SpamWord"]. "'=> 'i'";
$counter++;
}
}
} else {
echo "Error!";
}
$conn->close();
?>
I've read and tried more than 10 solutions found in the web and here at stackoverflow, however none of them worked. I've really got desperate and I cannot get through this without your help guys.
Edit
For example I tried with this solution, but it didn't work:
while ($row = mysql_fetch_array($result))
{
$new_array[$row['id']]['SpamWord'] = $row['SpamWord'];
}
foreach($new_array as $array)
{
echo $array['SpamWord'].'<br />';
}
Thank you all in advance,
Denis Saidov

Try like below:-
$sql = "SELECT `SpamWord` FROM spamWords";
$result = mysqli_query($conn ,$sql) or die(mysqli_error($conn));
$resultArray = array(); // create an array
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$resultArray[$row["SpamWord"]] = 'i'; // assing value
}
} else {
echo "Error!";
}
echo "<pre/>";print_r($resultArray); // print array
$conn->close();
Note: Here you will get your original array containing all SpamWord values comes from database.thanks

PHP array's are like dictionnaries (a list of key/value pairs)
First, before your loop, create your array empty:
$new_array = Array();
while...
Then for each column, you append the column value as a new key for the array
$new_array[$row['SpamWord']] = "i";
As in your example, I put "i" as the value for each array's row.

Related

PHP visualize MySQL select last n values [duplicate]

This question already has answers here:
Get all rows as an array of objects without a loop using MySQLi
(3 answers)
How to get single column values using MySQLi?
(4 answers)
Closed 2 years ago.
I'd like to visualize last 144 temperature data from MySQL database on my website. Now I have the following code:
<?php
$servername = "localhost";
$username = "_accounts";
$password = "---";
$dbname = "_accounts";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `t` FROM `WbabZwvgf` ORDER BY `id` DESC LIMIT 144";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$t = $row["t"];
}
} else {
echo "0 results";
}
$conn->close();
Now if I echo $t after i have declared in "while" like this:
while($row = $result->fetch_assoc()) {
$t = $row["t"];
echo $t." ";
}
seems everything OK, but I can't save each values as php variables like $t1=t[0], $t2=t[1], $t3=t[2]...etc, even during the "while". Could you help me how to save the selected data into PHP variables?
Try
$t = array();
while($row = $result->fetch_assoc()) {
$t[] = $row["t"];
}
var_dump($t);
You should use an array. But the correct answer for your question is:
$i = 1;
while($row = $result->fetch_assoc()) {
${'t'.($i++)} = $row['t'];
}
echo $t1;
echo $t2;
--
Thanks for the minus. But read his question correctly. He asks for $t1, $t2 and so on.
And now consider which answer is the correct one. The one with the array certainly not.

Create nested JSON objects using PHP

I have the following MySQL table:
id desc qty
--------------------
10 abc 5
20 xyz 12
30 qwe 9
How can I use PHP/MySQL query to create the following JSON file?
{
"10":{"desc":"abc","qty":"5"},
"20":{"desc":"xyz","qty":"12"},
"30":{"desc":"qwe","qty":"9"}
}
Here is my attempt
$query="SELECT id,desc,qty FROM table";
$result = #mysql_query($query);
while ($row=mysql_fetch_object($result))
{
$data[]=$row;
}
echo json_encode($data);
The result is an array and I am not sure how to display it correctly
[
{"id":"10","desc":"abc","qty":"5"},
{"id":"20","desc":"xyz","qty":"15"},
{"id":"30","desc":"qwe","qty":"9"}
]
Any help is appreciated
There are many ways to achieve this.One of them is below. changes your database credentials and table name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM TableName";
$result = $conn->query($sql);
$results_array =array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results_array[$row['id']] = array(
'desc'=>$row['desc'],
'qty'=>$row['qty'],
);
}
} else {
echo "0 results";
}
$json_array = json_encode($results_array);
echo $json_array;
Results should be look alike
{
"1":{"desc":"abc","qty":"12"},
"2":{"desc":"xyz","qty":"54"}
}
Thanks for editing your question. You can change the structure of your results with another loop:
foreach($data as $d)
$r[$d->id] = ['desc' => $d->desc, 'qty' => $d->qty];
$data = $r;
right above:
echo json_encode($data);
or you could adjust your while loop to get the same result:
$data[$row->id] = ['desc' => $row->desc, 'qty' => $row->qty];
or you could use array column (again right above json_encode):
$data = array_column($data, null, 'id');
The last example produces a slightly different output, but you can still use it in many situations. If you can't the first two options are preferable.

How to get only last iteration value while fetching data from the database,I've tried Getting values as JSON format

Here's what i tried.
I've Tried fetch the data from DB.It shows data from the start of the iteration to the End of iteration.I need only last iteration value.I'm a complete noob. A help would be appreciated
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
$conn = new mysqli($servername, $username, $password, $dbname);
$myarray=array();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myarray[]= $row;
// echo "<pre>";
// print_r($myarray);
echo "<pre>";echo json_encode($myarray);
// echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Description :" . $row["description"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Change your SQL query to
SELECT id, name, description FROM products order by id desc limit 1
That will work for you.
Finally, I got your point that what you want-
You need to get all record in one variable.Which you can encode at last
For that do like below:-
1.Initialize array outside of the loop
2.Assign each record to the array inside the loop
3.Encode array outside the loop
Do like below:-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
$conn = new mysqli($servername, $username, $password, $dbname);
$myarray=array();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM products";
$result = $conn->query($sql);
$myarray = []; //Initialize array outside of the loop
if ($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myarray[] = $row; //Assign each record to the array inside the loop
}
} else {
echo "0 results";
}
$conn->close();
echo json_encode($myarray);//Encode array outside the loop
?>
While it looks like a duplicate to me, I would suggest the following, assuming that you are not intending to sort the dataset from the DBMS.
Use mysqli_data_seek ( mysqli_result $result , int $offset ) to move cursor that traverses the dataset. So for your case it would be
$nor = mysqli_num_rows($result); //Number of rows
mysqli_data_seek($resutl, ($nor - 1)); //Indices are based on 0
Basically $nor contains the total number of records. So the index of the last ever record would be $nor-1.
Of course if you are sorting the dataset in your query using ORDER BY, then the best way to do this is appending ORDER BY id DESC LIMIT 1.

PHP - MySql SELECT WHERE value = string JSON

through a cURL connection, I can pick up data, from Json files, placed on a remote server. In particular, the codes of some products, which thanks to a foreach
foreach($data['results'] as $key=>$val){
$codici_hotel = $val['hotel_code'];
echo $codici_hotel.",";
}
I can see on video:
1074d0,19f726,1072ba,107104,183444,112438,15d8ab,1b326e,19d885,189b95,1071bf,107155,193e61,10aab2,138752,18dd7d,19d7f9,117b0d,1071b8,1398c4,107039,110851,107124,110669
Now I need to use that string to run a select on a local database, such as:
$sql = "SELECT * FROM hotels WHERE code = ('$codici_hotel')";
What is the correct sql string?
Thanks for your help
CODE UPDATE USED
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT name FROM hotels WHERE code IN ('$codici_hotel')";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$nome_hotel = $row2["name"] ;
}
} else {
echo "0 results";
}
$conn2->close();
echo $nome_hotel;
You have to convert your all codes in string enclosed with '. Then use IN clause of mysql. change your code as below
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$sql = "SELECT * FROM hotels WHERE code IN ($codici_hotel)";

Echo text only if MySQL value matches

I have two rows in my MySQL data that I would like to have code echoed only if the MySQL row data is equal to '1' (as opposed to '0'). Here's the code so far, which seems to have some severe errors:
$query = "SELECT 162, 164 FROM search WHERE title = $title";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
if ($row["162"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
if ($row["164"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
}
$result->close();
}
$mysqli->close();
As it says in the code above the two rows are "162" and "164" in the database.
Use:
if ($row["162"] == 1)
Instead of:
if ($row["162"] = 1)
and:
if ($row["164"] == 1)
I tried for you something like this if it gives you some idea:
$host = "localhost";
$user = "myusername";
$pass = "mypassword";
$database = "WorldEngine";
$mysqli = new mysqli($host, $user, $pass, $database);
$title = "My Good News";
$query = "SELECT `162`, `164` FROM search WHERE title = '$title';";
if ($result = $mysqli->query($query)) {
$i = 0;
while ($row = $result->fetch_row()) {
if ($row["162"] == 1) {
echo '<div id="162link' . $i . '">1.6.2</div>';
}
if ($row["164"] == 1) {
echo '<div id="164link' . $i . '">1.6.4</div>';
}
$i++;
}
$result->free();
}
$mysqli->close();
The index $i is appended to the div ID in order to produce unique DOM element ID's in the HTML document. I would also suggest you to change your numerical column names into alphabet-starting names like c162, c164, ...
Hope this will help you.

Categories