some problems with in_array function - php

Hi I am trying to use in_array, I think my syntax is correct,
but it says "Wrong datatype for second argument"
My code is
$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
while($row = mysqli_fetch_array($result))
{
if (in_array($row['ProductID'], $filter))
{
}
}
My idea is to find out if the ProductID from Products Table is in the Order Table.
Could someone helps me, Thanks :-)

$filter isn't an array; it's a mysqli_result object:
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
I think you want to iterate over that, add each ProductID to a new array, and then pass that array to the in_array function like so:
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
$product_ids = array();
while ($row = $filter->fetch_assoc())
{
$product_ids[] = $row['ProductID'];
}
$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
while($row = mysqli_fetch_array($result))
{
if (in_array($row['ProductID'], $product_ids))
{
}
}

Your code is failing because $filter is a MySQLi result resource, not an array. Really, this is better accomplished with a simple inner join between the two tables. If a ProductID does not exist in Orders, the INNER JOIN will exclude it from the result set in the first place.
$sql = "
SELECT Products.*
FROM
Products
INNER JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
If instead you want to retrieve all the Products, and simply have an indication of whether it has an active order, use a LEFT JOIN and test if Orders.ProductID is null in the SELECT list:
$sql = "
SELECT
Products.* ,
/* No orders will print 'no-orders' in a pseudo column called has_orders */
CASE WHEN Orders.ProductID IS NULL THEN 'no-orders' ELSE 'has-orders' AS has_orders
FROM
Products
LEFT JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
// And the column $row['has_orders'] will tell you if it has any...
In this case, you may test in a loop over your rowset whether it has orders:
foreach ($results as $r) {
if ($r['has_orders'] == 'has-orders') {
// this has orders
}
else {
// it doesn't...
}
}

Related

MySQL: Get all Columns of Table starting with name "ctr_" and value 1

I have a country restriction on products in my shop and a slow query to select all country-columns with a value of 1 from the table product.
I select all active countries in my shop:
$ids = select id from country where active = 1;
Then I select all countries, which are active in a product:
foreach $ids as $id { select ctr_{$id} from product where ctr_{$id} = 1;
Is there a faster way to get the columns starting with ctr_* and which value is equal to 1?
Try the following
// first get the columns
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='product' AND COLUMN_NAME LIKE 'ctr_%'";
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn),E_USER_ERROR);
$cols = Array();
while($row = mysqli_fetch_row($result)) $cols[] = $row[0];
// then build the query
if(count($cols))
{
$query = 'SELECT '.implode(',', $cols).' FROM product WHERE 1 IN ('.implode(',',$cols).')';
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn), E_USER_ERROR);
while($row = mysqli_fetch_assoc($conn,$result))
{
// do something with the row
// ....
}
}

How to merge an array inside another array in php?

Im trying to merge or put an Array (called '$rows_ban') inside a sub item of another array (called '$rows') in a final array named '$rows_final'.
Im using array_merge but returns null inside 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[null]}
It should return the results in of the second query inside the 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}
PHP Script:
$rows = array();
$rows_ban = array();
$rows_final= array();
$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");
while($r = mysqli_fetch_array($result1)) {
$rows['date']= $r[2];
$rows['hour']= $r[3];
$rows['data'][]= null;
}
$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );
while($r = mysqli_fetch_array($result2)) {
$rows_ban['cod'] = $r[0];
$rows_ban['name'] = $r[1];
$rows_ban['total'] = $r[2];
$result3 = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod=".$r[0]." order by dates desc");
while($r = mysqli_fetch_assoc($result3)) {
$rows_ban['sub_data'][] = $r;
}
$rows_final = array_merge($rows['data'],$rows_ban);
// here im trying to merge the $rows_ban array inside the
$rows['data']
}
echo json_encode($rows_final);
Not sure if that's what you wanted to accomplish since your description is very poor and hard to understand.
$output = [];
$tmpRows = [];
$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output['date'] = $tmp[0]['sync_date'];
$output['time'] = $tmp[0]['sync_time'];
}
$result = mysqli_query($link, 'SELECT cod, name, total from totals ');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['cod'] = $tmp[0]['cod'];
$tmpRows['name'] = $tmp[0]['name'];
$tmpRows['total'] = $tmp[0]['total'];
$result = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod={$tmp[0]['cod']} order by dates desc");
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['sub_data'] = $tmp[0];
}
$output['data'] = $tmpRows;
}
print_r(json_encode($output));
Also array_merge doesn't work like you think it does. It returns merged array like it's name states. Regarding to your code, final result would be exactly $rows_ban encoded to json.
http://php.net/manual/en/function.array-merge.php

PHP SQL inner Join bool(false)

I am attempting to get a 'total weight' for items a character is carrying. I am doing this by selecting the quantity of items in the characteritem table and comparing the weight which is set in the item table and they are joined by the iid (item id) column
I have tried a lot of different methods to no avail so I have looked up join statements. The issue I have is why the $result would return bool(false) and then how I can get the weights to add up afterwards.
Here is the code I am working with currently:
$sql = "SELECT *
FROM `characteritem` WHERE `owner` = '$user'
INNER JOIN item ON characteritem.iid=item.iid";
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['characteritem.quantity'];
$itemweight = $row['item.itemweight'];
$itemtotal = $itemweight + $itemweight;
echo $itemtotal;
}
}
var_dump($result);
SQL is working fine now. I have got the weight and quantity and gotten the individual results. How would I get the values to add together for $itemtotal?
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid
WHERE `owner` = '$user'";
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['quantity'];
$itemweight = $row['itemweight'];
$itemtotal = $itemweight * $quantity;
echo $itemtotal;
}
}
Your SQL sintax is wrong, try
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid
WHERE `owner` = '$user'";
Try This
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid" WHERE `owner` = '$user';
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['characteritem.quantity'];
$itemweight = $row['item.itemweight'];
$itemtotal = $itemweight + $itemweight;
echo $itemtotal;
}
}
var_dump($result);

Only the last value from the list of values retrieved from MySQL is stored in the variable in codeigniter

I'm trying to fetch a list of values from MySQL table using query1 and then use them in query2 to fetch values. Query1 gives 4 values however Query2 gives output matching the last value of Query1.
Following is my controller code
public function example_ctl(){
$data['result'] = $this->some_model->example();
}
Following is my model code
public function example() {
$query = "select m.queue_id from agent_queue_mapping_table as m, user_table as u where u.id=m.user_id and m.company_id = ".$this->session->userdata('user_comp_id')." and u.id = ".$this->session->userdata('user_id');
$res = $this->db->query($query);
foreach ($res->result_array() as $value) {
$queue_ids = implode(',', $value);
}
$query_ticket = "select * from tickets_table where company_id = ".$this->session->userdata('user_comp_id')." and ticket_status = 'New' and queue_id IN (".$queue_ids.") ORDER BY id DESC LIMIT 3";
$res_ticket = $this->db->query($query_ticket);
return $res_ticket->result_array();
}
I'm not able to understand where I'm going wrong. Please help.
try changing your code into this
<?php
$queue_id = array();
foreach ($res->result_array() as $value) {
$queue_id[] = $value;
}
$queue_id = implode(",",$value);
?>
$queue_id is overridden inside the loop each time loop executes that is why you get last value
This is how I fixed this issue.
$query = "select m.queue_id from agent_queue_mapping_table as m, user_table as u where u.id=m.user_id and m.company_id = ".$this->session->userdata('user_comp_id')." and u.id = ".$this->session->userdata('user_id');
$res = $this->db->query($query);
foreach ($res->result_array() as $value) {
$queue_ids[] = $value['queue_id'];
}
$queue_id = implode(',', $queue_ids);
$query_ticket = "select * from tickets_table where company_id = ".$this->session->userdata('user_comp_id')." and ticket_status = 'New' and queue_id IN (".$queue_id.") ORDER BY id DESC LIMIT 3";
$res_ticket = $this->db->query($query_ticket);
return $res_ticket->result_array();

problem of while loop and array

$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
$result['recipe']=$recipe;
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'] = $ingredient;
}
echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.
$result['ingredient'] = $ingredient;
Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;
To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'][] = $ingredient;
}
print_r($result['ingredient']);
If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();
$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";
$resouter = mysql_query($query, $conn);
$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";
while( $recipe = mysql_fetch_array($resouter) )
{
if( $buffer_rec_id != $result['recipe.rec_id'] )
{
$recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);
$recipe_ingredients = array( );
$buffer_rec_id = $result['recipe.rec_id'];
$buffer_rec_name = $result['recipe.rec_name'];
$buffer_rec_cat = $result['recipe.rec_category'];
}
else
{
$recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );
}
}
$print_r($recipes);
This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.

Categories