Php explode then get the name row from a MySql Table - php

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);

Related

Add values from MySql database to an array through a loop

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');

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

how to display value of mysql sum query

I am trying to grab the total amount of sales made for a a single month
$aug11 = mysql_query("SELECT SUM(price) FROM table WHERE sales_date LIKE '08/%/2011' ");
when I echo $aug11 I get a resource id# error. I also tried to do this
$test1 = mysql_fetch_array($aug11);
and when I echo $test1 it just says "Array".
Is it absolutely necessary to place a GROUP by sales_date in the original query and then have a while loop that grabs the array and lets me echo the values?
I don't really need any other value except the sum of 'price' for the month of August.
Can someone please explain to me how I can display the value I need without a while loop?
use this to get the sum value
$test1[0];
echo $test1[0]; // returns the sum
$aug11 is not a query string, it is the result of a query. When you fetch an array from the result, it is an array of values, not a scalar. I think you want to do this:
$query = "SELECT SUM(price) FROM table WHERE sales_date LIKE '08/%/2011'";
$aug11 = mysql_query($query);
$row = mysql_fetch_array($aug11);
$test1 = $aug11[0];

sort an $array of ints by repetition and remove repetitions

i need to do this in php
lets say i have [1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,5,5,5,5,5,5,5,5,5,5,9,9,9,9,9]
i would like [1,5,9,2,3,4]
but my situation its a bit different, it's result from a mysql query
i have only an asociative atribute 'id_deseada', so i do now
while($row = mysql_fetch_array($result){
$t = $row['id_deseada'];
}
so instead of that, i guess i'd have to do domething like the first example; sort $result ordered by times of repetition and maybe beetter in a new array with a new field 'count' ?
This all begins because of this query:
SELECT articles.id as id_deseada,tags.* FROM articles,tags WHERE tags.id_article = articles.id AND tags.name IN ('name one','name two','form search inputs','...)
the problem is that returns one result for every tag and i want on result for every article..
First, generate the value array like this:
$vals = array();
while($row = mysql_fetch_array($result){
$vals[] = $row['id_deseada'];
}
Then, count and sort:
$valCounts = array_count_values($vals);
arsort($valCounts);
$result = array_keys($valCounts);
You can actually do it using an SQL query. For example, we have this table:
create table lol (id_deseada int);
insert into lol values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(2),(3),(4),(5),(5),(5),(5),(5),(5),(5),(5),(5),(5),(5),(9),(9),(9),(9),(9);
You can select the id_deseada's from the database sorting by repetitions by using grouping and ordering.
SELECT id_deseada FROM lol
GROUP BY id_deseada
ORDER BY COUNT(*) DESC
Result: 1, 5, 9, 2, 3, 4.

SELECT a few rows out of MYSQL

I need to select category ids from my sql database.
I have a variable $product_id and for each product id there are three rows in a table that i need to select using PHP.
If I do "SELECT * FROM table_name WHERE product_id='$prodid'"; I only get the one on the top.
How can I select all three category_ids which contain the same product_id?
I suppose you are using PHP's mysql functions, is this correct? I am figuring that your query is actually returning all three rows but you aren't fetching all of them.
$sql = "SELECT * FROM table_name WHERE product_id='$prodid'";
$r = mysql_query($sql, $conn); //where $conn is your connection
$x = mysql_fetch_SOMETHING($r); //where something is array, assoc, object, etc.
The fetch function gives only one row at a time. You say you need three so it needs to be executed three times.
$x[0] = mysql_fetch_assoc($r);
$x[1] = mysql_fetch_assoc($r);
$x[2] = mysql_fetch_assoc($r);
OR this would be better
while($curRow = mysql_fetch_assoc($r)) //this returns false when its out of rows, returns false
{
$categoryIds[] = $curRow['category_id'];
}
If this doesn't do it then your query is actually returning only one row and we need to see your tables/fields and maybe sample data.
SQL seems to be correct, but Why do you store product_id in categories table? if it's one-to-many relation it would be better to store only category_id in products table.
The SQL query is correct for what you want to do. It will select all the records in table_name with the field product_id = $prodid (not only 1 or 3 but any that matches the variable)
To select a few records you should use the LIMIT keyword
You should look inside your table structure and the variable $prodid to find problems.

Categories