merge two columns into an array - php

I want to merge two of my columns (yanlis_cevaplar, cevap_icerik) into an array and this code here gives me only one column in array when I print it (yanlis_cevaplar).
How do I fix it?
$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
$cevap1[] = $row; //grab everything and store inside array
}
$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
$cevap2[] = $row; //grab everything and store inside array
}
$tumcevaplar = array_merge($cevap1, $cevap2);
print_r($tumcevaplar);

Instead of making multiple queries, you can just fetch all the columns you want in one single query:
$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);
print_r($result);
This will result in something like this:
Array
(
[0] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
[1] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
... and so on ..
)
If this isn't what you want, then you need to show us an example.
I also recommend that you go through some basic SQL tutorials. How SELECT works is SQL 101. Here's one of many guides: https://www.tutorialspoint.com/mysql/mysql-select-query.htm

Related

Make Associative array with three element in array

I want three element in associative array, so far am successful in getting two in the array.
$sql = "SELECT * FROM `notification_table` ";
$resultsd1 = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($resultsd1);
$associativeArray = array();
while ($row = mysqli_fetch_assoc($resultsd1))
{
$associativeArray[$row['name']] = $row['price'] ;
}
foreach($associativeArray as $k => $id){
echo $k."=>".$id .' ';
}
And am getting the response like this
name1=>24.725 name2=>24.265
Now i want to add another column in array as well and the name is column is notification_check .
Am not able to get how to add three columns in a single array. Any help will be appreciated.
I want the output like name1=>24.725=>yes_notification name2=>25.43=>no_notification
And when i print_r($row) is show this output Array ( [sno] => 1 [name] => name1 [price] => 23 [notification_check] => yes_notification)
You could shorten this and use mysqli_fetch_all to create an array of all of the data and then manipulate the array using array_column to create the index...
$result = mysqli_fetch_all($resultsd1, MYSQLI_ASSOC);
$associativeArray = array_column($result, null, 'name');

Accessing array within an array in multiple database rows

I have a database structure that looks like the following:
I am trying to store the prices as a variables so that if I reference cage_linear_feet it will display 225.
I have tried the following code:
$sql = "SELECT * from pricing WHERE region = '$region' ";
$result = mysqli_query($conn, $sql);
while($rows=mysqli_fetch_assoc($result)){
$test[] = array($rows['field']=>$rows['price']);
}
print_r ($test);
This displays the following:
Array ( [0] => Array ( [cage_linear_feet] => 225 ) [1] => Array ( [cage_doors] => 1800 ) )
How do I access the "225" and "1800" values ensuring that if more records are added to the db it will still pick up the correct records. E.g as the $test1 which is cage_doors may change if records are added.
My opinion is that there is no point in wrapping the key-value pairs in their own separate arrays. I would change this line:
$test[] = array($rows['field']=>$rows['price']);
to this:
$test[$rows['field']] = $rows['price'];
The data association will be maintained in the key=>value pairs of one associative array ($test). So echo $test['cage_linear_feet'] ---> 225
If you want to set field as the array-key
$sql = "SELECT * from pricing WHERE region = '$region' ";
$result = mysqli_query($conn, $sql);
while($rows=mysqli_fetch_assoc($result)){
$test[$rows['field']] = $rows['price']);
}
print_r ($test);
No you should be able to reference by field like so:
echo $test['cage_doors'];
// returns 1800
Is the column 'field' unique? If so, do this:
while($rows=mysqli_fetch_assoc($result)){
$test[$rows['field']] = $rows['price'];
}
This will set the key in the array to the field, i.e.
Array('cage_doors' => 1800)
If its not unique, I recommend doing something like:
while($rows=mysqli_fetch_assoc($result)){
$test[$rows['field'] . '_' . $rows['pricing_id']] = $rows['price'];
}
This will set the key in the array to the field and the pricing id, which makes it unique, i.e.
Array('cage_doors_2' => 1800)

How to return an entire column as an array using PHP

I am trying to fetch a column from a database and display the entire contents as an array. I have so far been able to fetch only one of the entries from the table. I understand that I am fetching only $row[0] which is why i am getting only 1 element. I have tried to fetch all elements but I have not succeeded yet. can someone please let me know how to do it correctly? I have attached my code below.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT `current` FROM `monitor` ORDER BY `Sno.`";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_NUM);
printf("%s\n",$row[0]);
mysqli_close($con)
?>
PDO has a dedicated feature for your problem PDOStatement::fetchColumn.
So, from your question what I understand is- you want to fetch a database column and store this in a array which will make you to display the results.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT current FROM monitor ORDER BY Sno";
$result = mysqli_query($con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
$first_col = array_column($arr, 0);
print_r($first_col);
mysqli_close($con)
?>
i.e. if you have five entry to the database whose first column contains
the values like 'current1', 'current2', 'current3', 'current3' and 'current4' the result of this code will be
Array
(
[0] => current1
[1] => current2
[2] => current3
[3] => current4
[4] => current5
)

Associative array not storing first result from SQL

I have a database in MySQL and I'm using this query to select certain rows from it using PHP:
$q = "SELECT Number, Body
FROM boxes
WHERE Number BETWEEN '1' AND '4' ORDER BY Number ASC";
Then calling the query and initiating arrays:
$r = $mysqli->query($q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$array = array();
$content = array();
Then attempting to sort the results into an associative array where the 'number' is the key and the 'body' is the value.
while ($row = mysqli_fetch_assoc($r)) {
$array = array(
$content[$row['Number']] = $row['Body']
);
This works fine except it will not store the first value. This is the result of print_r($content);, missing the first row.
Array ( [2] => This is entry two [3] => This is entry three [4] => This is entry four )
I have tried running the SQL query within PHPMyAdmin and it returns all four rows as I would expect.
Does anyone have any ideas what I'm doing wrong?
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
You are getting first returned row by this line. You have to remove it and it will work properly.
mysqli_fetch_array and mysqli_fetch_assoc returning NEXT row on every call.

PHP MYSQL multidimensional array

I'm having major headaches trying to create a multidimensional array from two separate MySQL selects.... I've been searching here and Google all day and have to finally admit defeat and ask for some help (I'm a newbie as well which doesn't help!!!).
I have two tables, one which contains a single row result per id and another which can contain several rows for an id. What I'm trying to do is combine the two into a multidimensional array.
My code (poor as it may be) looks like this:
require 'php/phpConnection.php';
$sqlString1 = mysql_query("SELECT id FROM supportstaff_section1_a");
$firstArray = array();
$secondArray = array();
while ($r = mysql_fetch_assoc($sqlString1)) {
$applicantID = $r['id'];
$sqlString2 = mysql_query("SELECT educationalname FROM supportstaff_section5 WHERE id = '$applicantID'");
while ($x = mysql_fetch_assoc($sqlString2)) {
$secondArray[] = $x;
}
$firstArray[] = $r + $secondArray;
$secondArray = array();
}
print json_encode($firstArray);
mysql_close($con);
The result is this:
[{"id":"8m8wwy","0":{"educationalname":"GCSE - English"},"1":{"educationalname":"GCSE - Maths"}},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
But I think it needs to look something like this:
[{"id":"8m8wwy","Array2":"[{"educationalname":"GCSE - English"},{"educationalname":"GCSE - Maths"}]"},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
Anyway, how can I insert my second SQL Select into my first SQL Select for each ID.
Thanks for any advice/help.
EDIT
Taken from W3Schools.com:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
I'm trying to make it work like the above.
You need to get a little creative here. Something like the following would work as a join AND with multi-dimensional data:
<?php
require 'php/phpConnection.php';
// ======================================================================
// Create a join query (way faster than several separate ones!)
$sqlquery =
"SELECT SSSA.id, SSS5.educationalname" .
" FROM supportstaff_section1_a SSSA" .
" LEFT OUTER JOIN supportstaff_section5 SSS5 ON SSS5.id = SSSA.ID";
// ======================================================================
// Run the query and get our results
$resultarray = array();
if ($resource = mysql_query($sqlquery)) {
while ($curarray = mysql_fetch_assoc($resource)) {
// Create an array, if it doesn't exist
if (!isset($resultarray[$curarray["id"]]))
$resultarray[$curarray["id"]] = array();
// Add to the array, if not null
$curstring = (string) $curarray["educationalname"];
if ($curstring != "")
$resultarray[$curarray["id"]][] = $curstring;
}
mysql_free_result($resource);
}
// ======================================================================
// Convert from a keyed array to a standard indexed array (0, 1, 2, etc.)
$finalarray = array();
foreach ($resultarray as $id => & $data) {
// Start with just ID
$newarray = array(
"id" => $id
);
// Get the data, if we have any
if (count($data))
$newarray["educationalnames"] = & $data;
// Add to our final array and clear the newarray
$finalarray[] = & $newarray;
unset($newarray);
}
// ======================================================================
// Get the JSON of our result
$jsonresult = json_encode($finalarray);
// ======================================================================
// Echo it to test
echo $jsonresult;
// ======================================================================
// Close the database
mysql_close($con);
?>
And the resulting $jsondata would look like this (but not so unravelled of course):
[
{
"id": "8m8wwy",
"educationalnames": ["GCSE - English", "GCSE - Maths"]
},
{
"id": "wiL7Bn"
},
{
"id": "zAw6M1"
}
]
If you have an ID from the first Array, you can check for keys / values with this ID in the second Array.
If you want to get the key you should use
array_key_exists($string)
And if you want to get the value you should use
in_array($string)
You can use a foreach loop to execute this functions!

Categories