This is probably a stupidly easy question, but I'm suffering from brainfade ... I'm using a SELECT statement to pull data from a MySQL Database then looping through it with a WHILE loop to push the returned data to the array '$arr', using the code below;
$query="SELECT idBaptism as id, baptismDate as eventDate, concat(baptismForename,' ',baptismSurname) as name, churchName, tbLocation.idLocation as locationid, location, clat as lat, clng as lng FROM tbBaptism, tbLocation, tbChurch WHERE tbBaptism.idLocation=tbLocation.idLocation AND tbBaptism.idChurch=tbChurch.idChurch";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
My question is I want to append the text 'Baptism' onto the end of each row of the array, what's the easiest way to do this??
As an example, here is the sample output of two rows of the array produced from the code above using print_r;
Array ( [0] => Array ( [id] => 1 [eventDate] => 1874-03-08 [name] => Henry Stanley [churchName] => St. Leonards [locationid] => 28 [location] => Halwell, Devon, UK [lat] => 50.366001 [lng] => -3.720500 )
[1] => Array ( [id] => 2 [eventDate] => 1870-11-06 [name] => Valentine Joles [churchName] => St. John The Evangelist [locationid] => 27 [location] => East Horrington, Somerset, UK [lat] => 51.218143 [lng] => -2.600683 )
I want to add value pair on the end of each row, such as [type] => 'Baptism' ...
Simply push the new element to the fetched array $row and then push it to the array $arr, like this:
// your code
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$row['type'] = 'Baptism';
$arr[] = $row;
}
}
Related
Suppose that I have a table like this:
id name age birthplace
------------------------------
1 John 28 NY
2 Marry 23 LD
3 Mohamad 34 Malaysia
...
I do while loop like this:
$query = "SELECT name, age, birthplace FROM tableName";
$result = mysqli_query($dbc, $query);
$tableRows = array();
while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$tableRows[] = $rows;
}
echo '<pre>';
print_r($tableRows);//Print the table rows from array
echo '</pre>';
I've got:
Array
(
[0] => Array
(
[name] => John
[age] => 28
[birthplace] => NY
)
[1] => Array
(
[name] => Marry
[age] => 23
[birthplace] => Prozent Rabatt
)
[2] => Array
(
[name] => 45521
[age] => Bekleidung
[birthplace] => LD
)
[3] => Array
(
[name] => Mohamad
[age] => 34
[birthplace] => Malaysia
)
)
I would like to change the keys name, age, birthplace to 0, 1, 2 respectively.
I have read this link:
In PHP, how do you change the key of an array element?
But it seems that I do not need it as the function because it looks so advanced to me.
I also read this link:
PHP rename array keys in multidimensional array
But it just meant to change one key in one array only as I tested for my case.
Your help is appreciated.
Thanks,
using MYSQLI_ASSOC its return associative array if you replace it with MYSQLI_NUM in mysqli_fetch_array() it will return a result as you ask
$query = "SELECT name, age, birthplace FROM tableName";
$result = mysqli_query($dbc, $query);
$tableRows = array();
while($rows = mysqli_fetch_array($result,MYSQLI_NUM)){
$tableRows[] = $rows;
}
echo '<pre>';
print_r($tableRows);//Print the table rows from array
echo '</pre>';
I am trying to fetch one array from an Oracle database and another from a MySQL database.
But the arrays I get back are in different formats, and I am not able to display them in an HTML table.
$result = $instance->prepare("SELECT * from dd ");
$result->execute();
while ($row = $result->fetchAll(PDO::FETCH_ASSOC))
{
$rows2 = $row;
}
$array = oci_parse($conn, "SELECT * FROM DD");
oci_execute($array);
while($row=oci_fetch_array($array, OCI_ASSOC))
{
$rows1 =$row;
}
print_r($rows1);
print_r($rows2);
$output = array_merge($rows1,$rows2);
print_r($output);
Here $instance and $conn are the respective connection variables.
The outputs I get after printing the two arrays are:
Array from Oracle:
Array ( [CLIENTID] => 2 [CLIENTNAME] => dsd [PHONENO] => 53556535 [ADDRESS] => Mumbai [ROUTE] => 4323 )
Array from MySQL:
Array ( [0] => Array ( [ClientId] => 3 [ClientName] => PQR [PhoneNo] => 786483744 [Address] => Pune [Route] => 3329 ) )
And after merging I get this array:
Array ( [CLIENTID] => 2 [CLIENTNAME] => dsd [PHONENO] => 53556535 [ADDRESS] => Mumbai [ROUTE] => 4323 [0] => Array ( [ClientId] => 3 [ClientName] => PQR [PhoneNo] => 786483744 [Address] => Pune [Route] => 3329 ) )
How do I print this in a table in HTML format?
You can not just merge two arrays in this case.try code below;
$all = array();
$all[] = $rows1;
foreach($rows2 as $k2=>$v2) {
$new=array();
$new['CLIENTID'] = $v2['ClientId'];
$new['CLIENTNAME'] = $v2['ClientName'];
$new['PHONENO'] = $v2['PhoneNo'];
$new['ADDRESS'] = $v2['Address'];
$new['ROUTE'] = $v2['Route'];
$all[]=$new;
}
$str='<table><tr><th>CLIENTID</th><th>CLIENTNAME</th><th>PHONENO</th><th>ADDRESS</th><th>ROUTE</th></tr>';
foreach($all as $arr) {
$str.='<tr><td>'.$arr['CLIENTID'].'</td><td>'.$arr['CLIENTNAME'].'</td><td>'.$arr['PHONENO'].'</td><td>'.$arr['ADDRESS'].'</td><td>'.$arr['ROUTE'].'</td>';
}
$str.='</table>';
echo $str;
If $rows1 is an array-array like $rows2, you should iterate same loop for $rows1 also
I am trying to get values from MySQL array as alphabetically, and I want results like:
[B] => Array (
[id] => 6
[firstname] => Bon
[lastname] => Jone
),
Array (
[id] => 7
[firstname] => bon
[lastname] => doe
)
[H] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
[J] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
Here is the code of what I have tried.
edited
$result = mysqli_query($GLOBALS['conx'],"SELECT * FROM $users_table ORDER BY firstname ASC");
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$row['alphabets'] = ucfirst($firstname[0]);
$data[] = $row;
}
But it outputs like this:
[0] => Array
(
[id] => 6
[firstname] => Bon
[lastname] => Jone
)
[1] => Array
(
[id] => 7
[firstname] => bon
[lastname] => doe
)
[2] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
[3] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
How can I get output like this:
A
Adam Smith
Alan smith
B
Bone Doe
Bone Joe
J
John Smith
.... etc
ucfirst returns the entire string with the first letter capitalised, you'll need to grab just the first letter with substr first.
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$key = strtoupper($firstname[0]))
$data[$key][] = $row;
}
To get the output (roughly) like you want, try something like:
foreach ($data as $letter => $rows)
{
echo "<h1>{$letter}</h1>", PHP_EOL;
foreach ($rows as $row)
{
echo "<p>{$row['firstname']} {$row['lastname']}</p>", PHP_EOL;
}
}
Your attempt will not do what you want. To achieve this, you will have to create a nested array, then on each iteration check the first letter of the firstname. Check if that letter already exists as a key in the array, and create an item in your array with an empty array as its value, it if it doesn't, and then add the row data to it to that newly created empty array.
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
$firstLetter = strtoupper($row["firstname"][0]); // convert to upper case so all are the same
if (array_key_exists($firstLetter, $data) === false) $data[$firstLetter] = [];
// now just add the row data:
$data[$firstLetter][] = $row;
}
First use Order in your MySQL Query: ... ORDER BY firstname ASC
Create Arrays for Alphabets using PHP:
$Alphabetic_Array = array();
while ($row = mysqli_fetch_assoc($result)) {
$Alphabetic_Array[$row['firstname'][0]][] = $row;
}
First of all, I suggest you to sort records in your query, otherwise you have to sort resulting array before grouping it:
SELECT * from tablename
ORDER BY firstname ASC, lastname ASC
Then, you can use array_map to group your array:
$result = array();
array_map
(
function( $row ) use( &$result )
{
$result[strtoupper(substr($row['firstname'],0,1))][] = $row;
},
$data
);
(Note that we have to call $result by reference)
Now the $result is an array like this:
Array
(
[B] => Array
(
[0] => Array
(
[id] => 7
[firstname] => bon
[lastname] => doe
)
[1] => Array
(
[id] => 6
[firstname] => Bon
[lastname] => Jone
)
)
[H] => Array
(
[0] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
)
[J] => Array
(
[0] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
)
)
If you want/can use PDO instead of mysqli_, you can obtain desired result directly from MySQL query. Set your query in this way:
SELECT UPPER(SUBSTR(firstname,1,1)) as initial, tablename.* from tablename
ORDER BY firstname ASC, lastname ASC
and then, fetching in in this way:
$data->fetchAll( PDO::FETCH_ASSOC|PDO::FETCH_GROUP );
your $data will contain desired array, without need of additional processing.
The PDO::FETCH_GROUP option groups fetched results by first column returned by query, in your case the capitalized firstname first letter.
What about letting MYSQL do the logic?
SELECT * FROM users_table, SUBSTRING(firstName, 1, 1) as initial ORDER BY firstname ASC
Then you just can append each line to an array
while ($row = mysqli_fetch_assoc($result)) {
$Alphabetic_Array[$row['initial'] = $row;
}
It's just pseudo code but I think the idea is pretty clear
Hello i have a problem with the logic to have a multidimentional array for each while loops that i had. I do not know why is it not working.
i wanted to have like this as concept
data >
ser_id > 14
org_name > "org a"
ser_id > 15
org_name > "org b"
but the output is like this
Array
(
[data] => Array
(
[ser_id0] => 14
[0] => Array
(
[0] => Gannon University
)
[ser_id1] => 15
[1] => Array
(
[0] => Lions Club
)
[ser_id2] => 16
[2] => Array
(
[0] => Rotatory Club
)
)
)
Can you help me with the logic. Here is the code i worked on with rows loop fetched from db.
$rs = $this->crud->fetchResultSet("services");
$rows = array();
$i=0;
while($row = $rs->fetch_assoc()){
//$rows = arra
$ser_id = $row["ser_id"];
$rows["data"][$i] = $ser_id;
$orgrs = $this->crud->fetchSingleResultSet("organizations","ser_id",$row['ser_id']);
$j=0;
while($innrow = $orgrs->fetch_assoc()){
$rows["data"][$i][$j] = $innrow["org_name"];
$j++;
}
$i++;
}
use multidimensional array like this =>>
$a[$i]['ser_id']=$row["ser_id"];
$a[$i]['org_name']=$innrow["org_name"]
and restore data like this
$max=count($a[$i]);
for($i=0;$i<$max;$i++){
echo 'ser_id =>'.$a[$i]['ser_id'];
echo 'org_name =>'.$a[$i]['org_name'];
}
I have a particular mysqli query that returns an empty element at the 0th position in the result set array. This empty non-object element seems to cause problems when I try to loop through the result set to display to screen
$projAreas[] = array();
$projectID = $_GET['projectID'];
$sql = "SELECT *
FROM `areas` , `project_area_junc`
WHERE `areas`.`areaID` = `project_area_junc`.`areaID`
AND `project_area_junc`.`projectID` = $projectID";
$results = $conn->query($sql);
while($row = $results->fetch_object()) {
$projAreas[] = $row;
}
The result gives unwanted array element at position 0)
i.e. when I print_r($projAreas)
I get this:
Array
(
[0] => Array
(
)
[1] => stdClass Object
(
[areaID] => 56
[propertyID] => 14
[areaName] => Living Room
[areaInfo] => lots of windows - colonial style
[proj_area_juncID] => 10
[projectID] => 4
)
[2] => stdClass Object
(
[areaID] => 57
[propertyID] => 14
[areaName] => Kitchen
[areaInfo] =>
[proj_area_juncID] => 11
[projectID] => 4
)
Try this ....
$projAreas = array();
while($row = $results->fetch_object()) {
array_push($projAreas ,$row);
}
print_r($projAreas);
try this
$projAreas= array();
instead of
$projAreas[]= array();
you have declare the array $projAreas as well initialize it by [] which takes first index 0