php - converting objects into array - php

$sql = "SELECT name FROM students";
$result = $conn->query($sql);
According to code above the $result is an object which contains the values from database.
suppose there are two names in the database under the column "name" like name1 and name2
now what i want is to convert the object $result into an array which will contain name1 and name2 as array element like
$name_array = array('name1' , 'name2')
how can i do that ??

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// acess the each colum elements using $row["<col name>"]
//this will loop through all the rows
}
} else {
// no rows where fetched
}
That is $row = $result->fetch(); will store the values of a row
in the array $row with key as column names

Answering my own question
got a solution for my problem and realized that it's pretty basic and shouldn't have posted this question. this type of problem should be solved by oneself.
$query = "SELECT name FROM students";
if($query_run = mysql_query($query)) {
$name_array = array();
while($query_row = mysql_fetch_assoc($query_run)) {
array_push($name_array, $query_row['name']);
}
the array_push function will do the trick.
thank you.

Related

Fetch multiple records from php/mysql

I am fetching records as follows:
$aResult = array();
$sql = "SELECT notes FROM table WHERE user_id = '$user_id'";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)){
$aResult['query_result'] = $row;
}
This returns only the last record in the table. I need to return all records from the sql statement.
change you $aResult['query_result'] = $row; to $aResult['query_result'][] = $row;
You've override the result each time, so you just get one.
It seems your loop constantly overwrites the value and hence you will only ever seen the last row. I think you might see better results if you do something like:
while($row = mysqli_fetch_array($result))
{
$aResult[] = $row;
}
so that each new row gets appended to your array
Try with following code, currently You are initiating the values to the same array key :
$aResult = array();
$sql = "SELECT notes FROM table WHERE user_id = '$user_id'";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)){
$aResult['query_result'][] = $row;
}
for more Detail On Array

Php Build an Array from MySQL

I currently collect data like this :
$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'].$row['name'].$row['surname'].$row['email'].$row['dob'];
echo "<br />";
}
It outputs all the data in one line, like this
1maxpaynemax#hat.com24/07/1950
I want to build the data into a Array rather so it looks like this :
$fields = array(
'id' => '21890',
'name' => 'nick',
'surname' => 'moppy',
'email' => 'nick#moppy.com',
'dob' => '11-01-1965',
),
You already have your array:
$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
var_dump($row);
}
So I'm going to make an assumption here. That is that you only want id, name, surname, email and dob. If you want all the columns returned from the table and in the array, just return the SELECT to what it was.
$query = "SELECT id, name, surname, email, dob FROM applicants";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
// $row is now what your example array looks like
}
So there are 2 differences, first, the specified columns from the table. If you're actually wanting all of the columns returned (back to using * for example), but don't want all of the columns returned in your array, this won't work (but you haven't said either way) but #b0s3 first example will.
Second, the addition of the MYSQL_ASSOC parameter. This tells PHP to return an array with only the column name indicies as opposed to them AND numeric keys which doubles up the number of items in the array.
You should use this way.
$query = "SELECT * FROM applicants";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
$res[] = $row;
}
echo "<pre>"; print_r($res); echo "</pre>";

PHP/MySQL: fetch one result

This is my database:
This is the query:
SELECT * FROM users
Now when I do this:
$query = $connection->query($_GET['query']); // SELECT * FROM users
print_r($query->fetch_assoc());
I get this as output:
Array (
[id] => 3
[username] => karel )
Why does it not output id 4 and username ccscs?
When I a while loop:
while($row = $query->fetch_assoc()){
print_r($row);
}
This is happening because you don't give any order to your query so it automatically get first record. If you want to return last record you can order by id desc as follow
SELECT * FROM users ORDER BY id DESC
If you instead need to retrieve all records you will need to loop throw your records
while($row = $query->fetch_assoc())
{
print_r($row);
}
Based on new op info i would not fetch twice but one as follow
$fields = array();
while($row = $query->fetch_assoc())
{
print_r($row);
$fields[] = $row;
}
fetch_assoc() retrieves a single row from a result set. See here.
mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch a result row
as an associative array
You should use something like this :
while($row = $query->fetch_assoc()){
print_r($row);
}
That's because fetch_assoc() just fetches one row.
To get each row you can do it like this:
while($row = $query->fetch_assoc()){
print_r($row);
}

Php mysql query array stores 2 fields in each array index

When I try to mysql_fetch_row the array that is created contains 2 fields from my selection at each index. I would like to ask why is this happening?
<?php
$categoryid = $_GET['id'];
include('connect.php');
$query = "SELECT
Categories_SubCategories.IdCategory,Categories_SubCategories.idSub_Category,
Categories.Name, Sub_Categories.Name from Categories_SubCategories JOIN
Categories on Categories.idCategory = Categories_SubCategories.idCategory
JOIN Sub_Categories on Categories_SubCategories.idSub_Category =
Sub_Categories.idSub_Category
WHERE Categories_SubCategories.IdCategory = $categoryid";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for($i=0; $i<$rows; $i++){
$display = mysql_fetch_row($result);
echo "$display[3]";
}
?>
most PHP programmers use while() loop when they want to work with mysql_fetch_array().
Take a look at this sample code:
$query = mysql_query("SELECT id,name FROM tbl_members");
if (mysql_num_rows($query)) {
while ($result = mysql_fetch_array($query)) {
echo('User #'.$result['id'].' is: '.$result['name'].'<br />');
}
}
// Output can be something like this:
// User #1 is: John
// User #2 is: Sarah
replace mysql_num_rows with mysql_fetch_array or mysql_fetch_assoc

display all cells in a mysql column

I need all values from a table column put into an assoc array. I am having trouble finding the answer.
the table is only six rows deep.
example:
|--id--|--name--|--A--|--B--|--C--|
|--01--|--xl33--| 1.30| 2.45| 4.40|
i would like to get an assoc array for column B
name[xl33]=2.45
name[xl34]=....and so on
The trick is that the form will tell the script which column to fetch. A,B,C,D,E,F OR G
I know i could re-format the table and accomplish what i want but I need it structured the way i have it.( i have left out some columns for simplicity)
function return_column($letter){
$result = mysql_query("SELECT name, $letter FROM example") or die(mysql_error());
while($row = mysql_fetch_assoc( $result )) {
$return[$row['name']] = $row[$letter];
}
return $return;
}
$results = return_column('A');
print_r($results);
Something like :
$col = 'B';
$name = array();
$result = mysql_query("SELECT * FROM table") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$name[$row['name']] = $row[$col];
}
This creates an array $name and uses the name column as the key and the $col column for the value ...
You are looking for the mysql_fetch_assoc() function.
Example/
$query = $this->query($YOUR_QUERY);
$returnMap = array();
while ($row = mysql_fetch_assoc($query)) { array_push($returnMap, $row); }
Use mysql_fetch_assoc — Fetch a result row as an associative array.
while ($row = mysql_fetch_assoc($result)) {
$data[$row["column1"]]= $row["column2"];
..............
.........
}

Categories