Add values from MySql database to an array through a loop - php

I have been trying to set a while loop to add all the ids in which the user has 20 days into an array. Currently, it displays an error of undefined offset. How can I code the code so that it first gets the id of the first row with 20 days in the lastSeen column, then, second, the ids of the second row and then adds them to the array?
$get_email = mysqli_query($con, "SELECT id FROM users WHERE lastSeen='20'" );
$email = mysqli_fetch_array($get_email);
$num_days = mysqli_num_rows($get_email);
$i = 1;
$array_id = array();
while($i <= $num_days){
array_push($array_id, $email[$i]);
$i = $i + 1;
}

First of all, your code is confusing. You get IDs from the database but the names of the variables tell "email". Try to be consistent, it will help you later, when you read this code again.
Since you don't do any processing with the values you get from the database, you can use mysqli_fetch_all(). It returns all the rows from the record set at once in an array. Passing MYSQLI_ASSOC as its second argument tells it to use the column names (from the SELECT clause of the query) as keys in the arrays it creates from each row of the result set.
Next, the PHP function array_column() extracts only the values of column id into a new array that contains exactly the values you need:
$result = mysqli_query($con, "SELECT id FROM users WHERE lastSeen='20'");
// Get all the rows, indexed by column names
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Get only the 'id' column
$ids = array_column($rows, 'id');

Related

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.

select user id from a table, using results of an array in php

I have a table called users(user_id, name, surname). In my php code a get an array with values like that:
<?php
$array = array();
while($e = mysql_fetch_array($favorites)){
$like_users = $e['user'];
$array[]=$like_users;
}
$arstring = implode(' ',$array);
?>
I want to select surname and name from table users, that their user_id is equal to those numbers exists as values in $array. Any idea how to do this?
Try this query
$sql='select name,surname from user where user_id in(?,?.....?)'
The number of ? is equal to the length of the array.
Then use
$query=$con->prepare($sql);
$query->execute($array);
Then fetch the returned rows.
PS:Creating prepared statements with variable number of arguments have been asked before on SO and the method is same as I have described.
collect all user_ids from SQL Query in one Array, then compare this array with your existing array
<?php
$array = array();
while($e = mysql_fetch_array($favorites)){
// $e['user'] equal user_id
$array[$user_id]= $e['user'];
}
?>
we use $array[$user_id] to save each user_id to corresponding array index, then compare two array as you want

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];
}
}

Checking if a value is in the db many times

I have a table A, with just two columns: 'id' and 'probably'. I need to go over a long list of ids, and determine for each one whether he is in A and has probability of '1'. What is the best way to do it?
I figured that it would be best to have 1 big query from A in the beginning of the script, and after that when I loop each id, I check the first query. but than i realized I don't know how to do that (efficiently). I mean, is there anyway to load all results from the first query to one array and than do in_array() check? I should mention that the first query should had few results, under 10 (while table A can be very large).
The other solution is doing a separate query in A for each id while I loop them. But this seems not very efficient...
Any ideas?
If you have the initial list of ids in array, you can use the php implode function like this:
$query = "select id
from A
where id in (".implode (',', $listOfIds).")
and probability = 1";
Now you pass the string as first parameter of mysql_query and receive the list of ids with probability = 1 that are within your initial list.
// $skip the amount of results you wish to skip over
// $limit the max amount of results you wish to return
function returnLimitedResultsFromTable($skip=0, $limit=10) {
// build the query
$query = "SELECT `id` FROM `A` WHERE `probability`=1 LIMIT $skip, $limit";
// store the result of the query
$result = mysql_query($query);
// if the query returned rows
if (mysql_num_rows($result) > 0) {
// while there are rows in $result
while ($row = mysql_fetch_assoc($result)) {
// populate results array with each row as an associative array
$results[] = $row;
}
return $results;
} else {
return false;
}
}
for each time you call this function you would need to increment skip by ten in order to retrieve the next ten results.
Then to use the values in the $results array (for example to print them):
foreach ($results as $key => $value) {
print "$key => $value <br/>";
}
Build a comma separated list with your ids and run a query like
SELECT id
FROM A
WHERE id IN (id1, id2, id3, ... idn)
AND probability = 1;
Your first solution proposal states that:
You will query the table A, probabyly using limit clause since A is a table with large data.
You will place the retrieved data in an array.
You will iterate through the array to look for the id's with probability of '1'.
You will repeat the first three steps several times until table A is iterated fully.
That is very inefficient!
Algorithm described above would require lots of database access and unneccessary memory (for the temporary array). Instead, just use a select statement with 'WHERE' clause and process with the data you want.
You need a query like the following I suppose:
SELECT id, probably FROM A WHERE A.probably = 1
If i understood you correctly, you should filter in the SQL query
SELECT * FROM A WHERE A.probably = 1

Php explode then get the name row from a MySql Table

I know this has been talked about here before. However, my situation is a bit different and I'm so close.
I would like to explode an array of category id's from a news data table then get the category name from the category table.
Right now I am able to get the id's out and explode them just fine inside the while loop for the news data using:
$post_cats_data = $news_data['cat_id']; // 1,6,7,11
$post_cats_id = explode(",", $post_cats_data);
Now where I'm getting stuck is getting the news categories and echoing out the name.
$cat_count = count($post_cats_id);
$i = 0;
foreach($post_cats_id as $cat_id){
$cat_qry = mysql_query("SELECT * FROM news_categories WHERE `cat_id` = '$cat_id'") or die(mysql_error());
$cat_title_row = mysql_fetch_row($cat_qry) or die(mysql_error());
$i++;
$write_cat .= $cat_title_row['cat_name'] ;
if($i<$cat_count){
$write_cat .= ', ';
}
}
The idea is that this will get the category names from the category tables that were exploded and will add a comma back to the end of everyone but the last one. I am unable to get the category name and when I return the ID it loops though the id for all the news.
I know this is a simple problem, I'm just new to using loops.
mysql_fetch_row returns an array indexed at 0, so $cat_title_row['cat_name'] will not give you the desired results. Use mysql_fetch_assoc instead and it should work fine.
From PHP manual:
mysql_fetch_row() returns an numerical array of strings that corresponds to the
fetched row, or FALSE if there are no
more rows.
mysql_fetch_row() fetches one row of
data from the result associated with
the specified result identifier. The
row is returned as an array. Each
result column is stored in an array
offset, starting at offset 0.
you could just use mysql_result like this:
$cat_title = mysql_result(mysql_query("SELECT cat_name FROM news_categories WHERE `cat_id` = '$cat_id'"),0);
if you want them all in a comma delimited list you could use implode like this:
$cat_titles = array();
foreach($post_cats_id as $cat_id){
$cat_title = mysql_result(mysql_query("SELECT cat_name FROM news_categories WHERE `cat_id` = '$cat_id'"),0);
$cat_titles[] = $cat_title;
}
$comma_cat_titles = implode(',',$cat_titles);
To get it all done in a single query you could do something like:
$cat_titles = mysql_result(mysql_query("SELECT GROUP_CONCAT(`cat_name` SEPARATOR ',') FROM `news_categories` WHERE `cat_id` IN (".$post_cats_data.")"),0);

Categories