MySQL SELECT WHERE id IN() get num_rows - php

I use this code to show category from database
$select_newscats = $mysqli->query("SELECT * FROM news_cats order by ord_show asc");
while ($rows_newscats = $select_newscats->fetch_array(MYSQL_ASSOC)){
$id_newscats = $rows_newscats ['id'];
$title_newscats = $rows_newscats ['title'];
$ord_show_newscats = $rows_newscats ['ord_show'];
$icon_newscats = $rows_newscats ['icon'];
$kind_newscats = $rows_newscats ['kind'];
$description_newscats = $rows_newscats ['description'];
//here is my data
}
i have in news table row for categoies it's name is cats and i insert data inside it like that 1,5,6,8
and i use this code to count news inside each cat
$select_newsnum = $mysqli->query("SELECT id FROM news where $id_newscats IN (cats)");
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
$num_newsnum = $select_newsnum->num_rows;
it gets only first value for example if i have this values 1,5,6,8 it gets only 1 the first value

I would do the counting in a single sql call, not with php logic and separate sql calls. For this I would join the 2 tables using left join and use a join condition instead of an in clause:
SELECT nc.id, nc.title, nc.ord_show, nc.icon, nc.king, nc.description, count(n.id) as newsnum
FROM news_cats nc
LEFT JOIN news n ON nc.id=n.cats
GROUP BY nc.id, nc.title, nc.ord_show, nc.icon, nc.king, nc.description
ORDER BY nc.ord_show asc
Obviously, make sure that the join condition is the right one. When you loop through the resultset, the number of news per category will be in the newsnum field.

$select_newsnum = $mysqli->query("SELECT id FROM news where $id_newscats IN (cats)");
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
$num_newsnum = $select_newsnum->num_rows;
Here $rows_newsnum will only return the first row in the database.
Fetch Array only returns one row at a time, and then moves the row pointer forward. For example the following code on the dataset you provided (1, 5, 6, 8).
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
echo $rows_newsnum["id"]; // Will print 1
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
echo $rows_newsnum["id"]; // Will print 5
What you need to do is move it into a while loop (like your first example) to get to access each row, like below:
while($row = $select_newsnum->fetch_array(MYSQL_ASSOC)) {
echo $rows_newsnum["id"] . ", ";
}
// Will produce:
// 1, 5, 6, 8,
If you just want to get a count
Your existing code should work fine. And you can omit the call to fetch_array.
$num_newsnum = $select_newsnum->num_rows;
echo $num_newsnum; // Will display 4
Read more about fetch_array on the PHP documentation:
http://php.net/manual/en/mysqli-result.fetch-array.php
Hope this helps.

Related

How to get specific data from table1, use it in table2

I'm trying to get specific rows in table 1 (stellingen). I want to store these rows to specify the rows im interested in for the second table (stelling). So lets say table 1 has 5 rows where stelling ID matches REGIOID = 5. These IDS from stelling ID I want to use to fetch the data from the second table. see the code to see what I tried. I'm not managing to find a way in order too make this happen.
So maybe too be clearer because people always say im not clear:
There are two tables. they both have a matching column. Im trying to tell the second table I want data but only if it matches the data of the first table. Like a branch of a tree. Then, I want to output some data that's in the second table.
I've tried something like this before:
SELECT
*
FROM
table2
LEFT JOIN
table1 ON
table1.ID = table2.table1_id
I've tried to create a while loop to get the data before(after the first if statement and the last += was for the variable $amountofstellinge):
$amountOfStellinge = 0;
while ($amountOfStellinge<5){
mysqli_data_seek($result, $amountOfStellinge);
Here is the code what it looks like now, its wrong, i've been messing with t a lot, but maybe it shows you what I'm trying to achieve better.
if($result = mysqli_query($con, "SELECT * FROM stellingen WHERE REGIOID=1;")) {
$row = mysqli_fetch_assoc($result);
$stellingid= $row["Stelling_ID"];
//checking.. and the output is obviously not what I want in my next query
printf($stellingid);
//defining the variable
$Timer=0;
$sql1="SELECT * FROM stelling WHERE stelling_iD=$stellingid ORDER BY Timer DESC;";
$records2 = mysqli_query($con, $sql1);
$recordscheck = mysqli_num_rows($records2);
//max 5 data
if ($recordscheck < 5){
while ($stelling = mysqli_fetch_assoc($records2)){
//At the end, i would like to only have the data that is most recent
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}}
$recordscheck+=1; } // this is totally wrong
EDIT:
I've tried this, #noobjs
$Timer=0;
$sql1="SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.ID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer LIMIT 5 DESC ;";
$records2 = mysqli_query($con, $sql1);
printf($records2);
while ($stelling = mysqli_fetch_assoc($records2)){
$Timer = date('d F', strtotime($stelling['Timer']));
echo "<p><div style='color:#ED0887'>".$Timer.":</div><a target = '_blank' style='text-decoration:none' href='".$stelling['Source']."'>".$stelling['Title']."</a></p>";
}
with this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in
EDIT for more clarification
Here is some sample data
The expected results is:
every page has uses data from a different REGIOID. I expect the page to show data from the table stelling(Table 1). Accordingly to the REGIOID (Table2)
if i understand right:
SELECT
*
FROM
stelling
LEFT JOIN
stellingen
ON
stelling.stellingID = stellingen.stelling_id
WHERE
stellingen.REGIOID=1
ORDER BY stelling.Timer DESC LIMIT 5 ;

php loop start over when num_rows==0

I'm trying to write a php code to select form tables:
books
images
Some books does not have an image, so I want to skip it and select another book.
I have wrote this code but it does not work with me perfectly.
Now I'm getting only 5 records! it must be 6 as I limited in the book select query.
$slider_sql = "select * from books limit 6";
$slider_result = $conn->query($slider_sql);
while($slider_row = $slider_result->fetch_assoc()) {
extract($slider_row);
$img_sql = "SELECT big_img FROM images WHERE book_id = '$id'";
$img_rs = $conn->query($img_sql);
$img_row = $img_rs->fetch_assoc();
if ($img_rs->num_rows == 0)
continue; //--> here I want to start while again to select another book.
echo $book_name.'<br>';
echo $img_row['big_img'].'<br>';
}
Thanks for your help and time!
Instead of having a sub-query in a loop (which is nearly ALWAYS a bad idea!), use a JOIN instead, which simplifies it to one query instead of two. Then set a condition that big_img should not be empty. This guarantees that you will only find rows where there's an image matching the book. LIMIT will still only ensure the return of 6 rows. <> in MySQL is the same as !=.
$slider_sql = "SELECT b.book_name, i.big_img
FROM books b
JOIN images i
ON i.book_id=b.id
WHERE i.big_img <> ''
LIMIT 6";
$result = $conn->query($slider_sql);
while ($row = $result->fetch_assoc()) {
echo $row['book_name'].'<br>';
echo $row['big_img'].'<br>';
}
MySQL JOIN

MySQL duplicates results even after using DISTINCT every time I try to show more than one field of the same table

I have a MySQL query that shows a list of items after joining two tables:
SELECT contenidos.tituloContenido FROM contenidos
JOIN cursosContenidos ON cursosContenidos.contenidoID = contenidos.contenidoID
WHERE cursosContenidos.cursoID = ?;
There's no problem with this query, but, when I change it to show another field of the contenidos table, the results are duplicated.
So they get duplicated when doing:
SELECT contenidos.contenidoID, contenidos.tituloContenido FROM contenidos
JOIN cursosContenidos ON cursosContenidos.contenidoID = contenidos.contenidoID
WHERE cursosContenidos.cursoID = ?;
I've tried adding a GROUP BY cursosContenidos.contenidoID clause, and DISTINCT as well, but they keep appearing duplicated. Any idea on why?
To retrieve the results, I'm using PHP:
$mostrarContenidos = $conectar1->prepare("
SELECT contenidos.tituloContenido FROM contenidos
JOIN cursosContenidos ON cursosContenidos.contenidoID = contenidos.contenidoID
WHERE cursosContenidos.cursoID = ?;
");
$mostrarContenidos->bindParam(1, $cursoID);
$mostrarContenidos->execute();
$contenidos = $mostrarContenidos->fetch(PDO::FETCH_ASSOC);
if ($contenidos) {
echo '<h2>Contenidos del Curso</h2>';
foreach ($contenidos as $value) {
echo 'Id: '.$contenidos['contenidoID'].'<br>';
echo 'Title: '.$contenidos['tituloContenido'].'<br>';
}
} else {
echo 'error retrieving results';
}
The expected result is:
Id: 1
Title This is my super title
What I get:
Id: 1
Title This is my super title
Id: 1
Title This is my super title
Your SQL query is most likely not returning multiple rows - you are only outputting it twice. This is because your foreach statement loops over each column in the single row you've fetched, rather than each row of the result set.
To clarify a bit further, this line just fetches the first (and probably only) row:
$contenidos = $mostrarContenidos->fetch(PDO::FETCH_ASSOC);
The foreach loop goes through each column in the row, and outputs info about the whole row for each column.
If you want $contenidos to be an array of all rows, you could do this instead:
$contenidos = $mostrarContenidos->fetchAll(PDO::FETCH_ASSOC);
The problem is not in the query, but in the php.
In your foreach-loop you assign the result-array-elements to $value, but then you don't use $value.
You should use :
echo 'Id: '.$value['contenidoID'].'<br>';
echo 'Title: '.$value['tituloContenido'].'<br>';
This should do it: GROUP BY contenidos.contenidoID, contenidos.tituloContenido
Should work with distinct
SELECT distinct contenidos.contenidoID, contenidos.tituloContenido FROM contenidos
JOIN cursosContenidos ON cursosContenidos.contenidoID = contenidos.contenidoID
WHERE cursosContenidos.cursoID = ?;

SQL Query Grabbing data from two tables

My code right now is this
$extract = mysqli_query($dbc, "SELECT * FROM items");
$numrows = mysqli_num_rows($extract);
while($row = mysqli_fetch_assoc($extract)) {
$id = $row['i_id'];
$iname = $row['i_name'];
echo "<tr><td><a href='capture.php?item_id=$id'>$iname</a></td><td>Incomplete</td></tr>";
}
What i want to do is run a check to see if the item has already been completed.
I have a separate table that contains the information, for instance say that Item 1 has been completed then I would like to be able to change my echo to something like:
echo "<tr><td>$iname</td><td>Complete!</td></tr>";
How would I accomplish this? Would I need to use some form of a join statement?
I want to be able to display all the items in the table but not duplicate them i initially thought that an if statement on the echo to see if item complete then do this else do that
Here are the two tables
Items item_collection
------ ---------------
i_id i_id
i_name complete
caption
image
c_id
g_id
You can use join condition like this (assuming complete is a varchar field)
SELECT a.i_id, a.i_name,
CASE WHEN i_status = '1' THEN 'Complete!' ELSE 'Incomplete' END AS complete_status
FROM items a
LEFT OUTER JOIN item_collection b ON a.i_id = b.i_id
select
case
when ic.complete = 1 then 'Complete'
else 'Incomplete'
end as item_status
from items i
left join item_collection ic on i.i_id = ic.i_id
where i.i_name = 'your_item_name'
Assuming that ic.complete = 1 when item is complete.
Something along the lines of SELECT * FROM table1 WHERE table1.id not in (SELECT Id FROM table2)

loop through mysql_query and replace value OR 1 query to do work

I am running a sql query, that pulls the id, catid, name, subof from two tables using inner join.
select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name
Now this results everything i need but I need to loop through the result and do another sql query for the subof value (which is a value, the value being a ID number of the shop_cat). I need to pull the catname of the subof value #, then update the result/array field subof to the name of the cat.
So if the original query gave me a value of 15 for subof, it would do a select catname from shop.cat where id='15' i would take the catname from that query and then update subof = catname for every value in the original result that has a subof value.
EDIT 3/23/13 12:30pm MST: Using more of the code that Opeyemi wrote, to explain more of what I need. I am not sure how else to explain it...
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
while(list($shopid, $catid, $name, $catname, $subof) = mysql_fetch_array($r)) {
$getname = mysql_query("select catname from shop_cat where id='$subof'");
$rowname = mysql_fetch_assoc($getname);
//code to update array to change value of $subof to new $rowname['catname']
}
The DB query runs, gets me my values.
I then need to run a loop of some kind, which will loop through every result PHP aquired from the query. This loop will take the subof value (which is a integer ID number) then run a query to get the value catname of that integer value. Then the loop will update the current result and change the subof value from the integer to the catname pulled from the DB in the loop.
I do not need to update the database at anytime, I need to update the result/array from the first query.
What you need to do is to store the resultset in an array and replace within the array.
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
$dataset = array();
// Store result in an array
while($assoc = mysql_fetch_assoc($r)) {
$dataset[] = $assoc;
}
// Update array
foreach($dataset as $data) {
$getname = mysql_query("select catname from shop_cat where id='{$data['subof']}'");
$rowname = mysql_fetch_assoc($getname);
// replace data
replace_dataset($data['subof'], $rowname);
}
function replace_dataset($key, $newname) {
global $dataset;
foreach($dataset as $k => $data) {
if ($data['id'] == $key)
$dataset[$k]['subof'] = $newname;
}
}
Are you asking how to do this in PHP or what? If you are looking for how to loop results in PHP it is as simple as this
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
while(list($shopid, $catid, $name, $catname, $subof) = mysql_fetch_array($r)) {
// the values from the query are assigned to the variables
// $shopid, $catid, $name, $catname, $subof in that order already
mysql_query("update shop_cat set subof=catname where id='$subof'");
// My interpretation of your query can be wrong though
// But you should get the idea
}
You can use mysql_fetch_assoc() or mysql_fetch_array() or mysql_fetch_row() functions to fetch the row and can put your looping concept on it.
After that you can use mysql_fetch_field() to fetch field subof and id from it.
and update the database after that
You can check the following links
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
http://www.php.net/manual/en/function.mysql-fetch-field.php
I hope you get some idea.

Categories