Read data from all rows in column PHP MySQL - php

I am doing some work that requires me to add the data from a specific column, say Column 1, to a PHP array. I can get the data from the first row in Column 1, but it stop there. How do I collect that columns data from every row in the table?

You have to loop over the result set in a while loop:
$result = mysql_query('SELECT...');
$data = array();
while(($row = mysql_fetch_array($result))) {
$data[] = $row['columnName'];
}
Every call to mysql_fetch_array will get the next row of the result set. If there is no row anymore, it will return null and the loop stops.
The documentation provides good examples.
Update:
Regarding duplicates: Either specify your SQL query correctly (preferred), e.g.
SELECT DISTINCT columnName FROM table
or use array_unique after you fetched all the data:
$data = array_unique($data);

//Variable declaration as a small sql query
$query = "select RowName FROM Table;";
//Execute Query
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
//Do Stuff
}

Related

get data from two tables and collect them in array and count rows of one table result

I had two tables named fixture_list and OneRecord where fixture_list has 3 columns named Team1, Team2, player whereas OneRecord has columns like Team1, Team2, id, status so here I want to select all the data of fixture_list and put them into array whereas I want to count the number of rows based on this where condition fixture_list.Team1=OneRecord.Team1 and
fixture_list.Team2=OneRecord.Team2 from OneRecord, actually I am not able to distinguish between selecting the data and putting it into the array and counting the number of rows because I just want to count the rows of one record only. I know things like joins and mysqli_multi_query() can be performed but do not know how...I want to perform this thing in single query please help.
<?php
require_once('connect.php');
$sql = "select * from fixture_list";
if($res = mysqli_query($con,$sql)){
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('players'=>$row[3],
'team1_name'=>$row[1],
'team2_name'=>$row[2]
));
}
mysqli_free_result($res);
}
echo json_encode (array("list"=>$result));
mysqli_close($con);
?>
You can use a sub_query to do this. I don't understand your question perfectly (try using capitals and punctuation marks), but this should be probably the format to use.
$sql = "SELECT `fixture_list`.`team1_name`,
`fixture_list`.`team2_name`,
(
SELECT count(`OneRecord`.`Team1`) as `total`
FROM `OneRecord`
WHERE `OneRecord`.`Team1` = `fixture_list`.`Team1`
AND `OneRecord`.`Team2` = `fixture_list`.`Team2`
) as `Total_Players`
FROM `fixture_list`
GROU BY `fixture_list`.`id`";
$result = array(); // keep this outside the while loop to ensure the array is made
if($res = mysqli_query($con,$sql)){
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)){
$result[] = $row;
}
}
This would give you a $result array as follows:
array(
'team1_name' => 'TEAMNAME1',
'team2_name' => 'TEAMNAME2',
'Total_Players' => INTEGER_VALUE
)
The INTEGER_VALUE is the number of rows from the subquery. You can edit the WHERE part of the subquery to your liking
Then you can do this to create a json object:
echo json_encode($result);
This will echo it, which is ideal if you use it with an Ajax function for example.

SQLite query not returning all result rows

I am trying to pull out a section of rows from a SQLite 3 database using the following code:
function getunsolved($user) {
$sql = "SELECT challenge FROM completed WHERE status = 0 AND username = '$user';";
$rez = $this->query($sql);
$temp = $rez->fetchArray(SQLITE3_NUM);
return $temp;
}
Unfortunately, the code is only returning 1 row, and should be returning 9 rows.
Running the above SQL code on the database, and substituting a valid username for $user returns the correct amount of rows, so I know the problem isn't the SQL code.
My table format is as follows:
username (TEXT), challenges (TEXT), status (INTEGER) (in that order, if it matters)
According to the manual:
SQLite3Result::fetchArray - Fetches a result row as an associative or numerically indexed array or both. By default, fetches as both.
So if you want to get all of the results, you should iterate over them and return the aggregated data:
$ret = array();
while($row = $rez->fetchArray(SQLITE3_NUM)) {
$ret[] = $row;
}
return $ret;

Php PDO request for data from the sum of a derived table column

Here is an SQL query that I am attempting to use in some php PDO code:
SELECT SUM(credit_hours) AS hours FROM(SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id ) AS major_credits
When I run this query on my database in SQL Workbench I get a derived table with a single column named
"hour" and a single row with the value 76 in it.
Here is the php code I'm using to try to get this same data stored in a variable $major_hours:
$result = $conn->prepare("SELECT * FROM students WHERE username = :un");
$result->bindParam(':un',$user);
$result->execute();
$data = $result->fetch(PDO::FETCH_ASSOC); //returns an associated array where the indices are the column names
$program = $data['program_id'];
$concentration = $data['concentration_id'];
//get the total number of credit hours in the student's major/concentration
$result = $conn->prepare("SELECT SUM(credit_hours) AS hours FROM(
SELECT Course_List.credit_hours FROM Program_Courses, Course_List
WHERE program_id= :pid and concentration_id= :conid
and fulfills_major=1 and Program_Courses.course_id = Course_List.course_id
) AS major_credits");
$result->bindParam(':pid',$program);
$result->bindParam(':conid',$concentration);
$result->execute();
$major_hours = $result->fetchColumn();
I know that the variables $user, $program, and $concentration all have legitimate values because when I echo those to the page, I get the correct result. However, echoing $major_hours gives absolutely nothing. What am I doing wrong?
Use fetch as you may guess it fetches the next row from a result set
The fetch_style parameter determines how PDO returns the row, in your case FETCH_ASSOC would be a good one since it returns an array indexed by column name as returned in your result set.
$row = $result->fetch(PDO::FETCH_ASSOC);//row is an associative array
$major_hours = $row['hours']; //access the column name hour
echo $majors_hours; //will print the hour value from db
I have not used sql workbench, but you may want to use isnull() or coalesce() on your SUM(credit_hours) expression. I think that should result in $major_hours showing 0.
Use this
$major_hours = $result->fetch(PDO::FETCH_ASSOC);
echo $majors_hours['hours'];
There is 2 way to return a data from database. fetch(PDO::FETCH_ASSOC) and fetchAll(PDO::FETCH_ASSOC). Fetch only return 1 row from database .. but fetchAll will return all row from the database query you make.
And (PDO::FETCH_ASSOC) it means will return the data with an array.

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

count columns from sql query

I'm trying to count the number of rows selected from a table by using the count() function. But it always returns either a '2' for every query with a row/rows selected or a '1' for every query with no row selected.
$sql_usb="select item_name from req_item where item_name='USB Dongle'";
$result_usb=mysql_query($sql_usb);
$row_usb=mysql_fetch_array($result_usb);
$sql_router="select item_name from req_item where item_name='Access Point/Router'";
$result_router=mysql_query($sql_router);
$row_router=mysql_fetch_array($result_router);
$sql_laptop="select item_name from req_item where item_name='Laptop'";
$result_laptop=mysql_query($sql_laptop);
$row_laptop=mysql_fetch_array($result_laptop);
$usb_inv=count($row_usb);
$router_inv=count($row_router);
$laptop_inv=count($row_laptop);
$total_inv=$usb_inv+$router_inv+$laptop_inv;
I've also tried adding isset() (i.e. $usb_inv=count(isset($row_usb));)
and mysql_num_rows() (i.e. $usb_inv=mysql_num_rows($row_usb));)
both give a result of 1.
You should use
SELECT COUNT(*) WHERE ....
Check the doc.
If you only need the total, then only 1 sql will be enough.
// please add error handing yourself.
$sql = "select count(*) from req_item where item_name
where item_name in('USB Dongle', 'Access Point/Router', 'Laptop')";
$result = mysql_query($sql);
$row = mysql_fetch_array($result)
$total = $row[0];
You have to use count in you mysql query like this
$SelectQuery = 'select Count(item_name) as [TotalUSB] from req_item where item_name='USB Dongle'
Then you can get the result by
$result = mysql_query($SelectQuery);
$row = mysql_fetch_array($result);
$USBCount = $row['TotalUSB'];
you should have used mysql_num_rows on result set.
like this.
$usb_inv=mysql_num_rows($result_usb);
$router_inv=mysql_num_rows($result_router);
$laptop_inv=mysql_num_rows($result_laptop);
this will give you proper output.
mysql_fetch_array is returning something like
$row[0] = ...;
$row[item_name] = ...;
If you are using count of an array, it will always return a two,
because it return an array with both index and associate key.
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
Despite the wrong usage of mysql_fetch_array,
you probably should just use a single query
$sql ="select item_name from req_item
where item_name in('USB Dongle', 'Access Point/Router', 'Laptop')";
after that,
$count = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
// do something else ...
// to get count for each item name
$count[$row["item_name"]]++;
}
You should use
$usb_inv = mysql_num_rows($result_usb);
instead of
$usb_inv=count($row_usb);

Categories