How to pass array parameters in url - PHP - php

I'm tryng to pass parameters in the url, but I receive this error:
*implode(): Invalid arguments passed in *
I know that the cause is that I pass a string as parameter instead of an array, but how can I do to pass the array directly?
My code:
$all_prod_cat="SELECT * FROM products GROUP BY product_category";
$run_all_prod_cat = mysqli_query($con,$all_prod_cat);
$sql= "SELECT * FROM products";
if(isset($_GET['product_category']) && $_GET['product_category']!="")
{
$risperpag = 16;
$limit = $risperpag * $_GET['p'] - $risperpag;
$prod_cat = $_GET['product_category'];
$sql.=",categories WHERE product_category IN ('".implode("','",$prod_cat)."') AND product_category = cat_id LIMIT $limit,$risperpag";
$get_cat_pro_total = "SELECT * FROM products,categories WHERE product_category IN ('".implode("','",$prod_cat)."') AND product_category = cat_id";
$run_cat_pro_total = mysqli_query($con,$get_cat_pro_total);
$num_cat_pro_total = mysqli_num_rows($run_cat_pro_total);
$npag = ceil($num_cat_pro_total / $risperpag);
$p = $_GET['p'];
echo "<ul>";
if($p!=1)
{
echo '<li class="numPagine">← Indietro</li>';
}
for($i=1;$i<=$npag;$i++){
if($p==$i)
{
echo '<li class="numPagine pagina_attuale">'.$i.'</li>';
}
else
{
echo '<li class="numPagine">'.$i.'</li>';
}
}
if($p!=$npag)
{
echo '<li class="numPagine">Avanti →</li>';
}
echo "</ul>";
}
The problem is when I set the urlencode parameter, I tried to serialize, but I get an other error. I think I should unserialize, but I don't know the exact point.
Thanks in advance.

It is possible to generate url with get params using http_build_query function.
$urlparams = [
'product_category' => [
'cat1',
'cat2',
'cat3',
'cat4'
]
];
echo http_build_query($urlparams);

Related

Php in_array with session

My PHP statement looks like this
$select_product= "SELECT * FROM `products` WHERE pro_name = '$page_name' and status = 'Active'";
$sql101=$dbconn->prepare($select_product);
$sql101->execute();
$wlvd101=$sql101->fetchAll(PDO::FETCH_OBJ);
foreach($wlvd101 as $rows101);
$product_id = $rows101->id;
// Gives me result of a sample id 101
Again I am another statement where I have fetched the ids of products from my cart. The statement looks like this:
$pidArr = array();
if(!empty($_SESSION['cart'])){
foreach($_SESSION['cart'] as $id=>$val)
{
$rate=$val['product_mrp'] * $val['qty'];
$total=$total+$rate;
$pidArr[] = $val['uid'];
$qtyArr[] = $val['qty'];
$webArr[] = $val['ppid'];
}
$all_cart_products = "'" . implode("','", $pidArr) . "'";
//echo $all_cart_products;
//It gives me a list of ids like this '100', '101', '102' etc
}
Now while using in_array, my statement is not working. The code looks like this:
$my_ids = $all_cart_products;
if (in_array("$product_id", $my_ids))
{
echo "Match Found";
}
else
{
echo "Match not found";
}
How to solve this problem?
This line $all_cart_products = "'" . implode("','", $pidArr) . "'" creates a string.
Which you then assign $my_ids = $all_cart_products; so $my_ids is also now a string.
Pass it $pidArr instead.

ext js store/model example .net -converting php/mysql to .netwebservier/sql

Afternoon all,
I am working through a tutorial from MASTERING EXT JS and am stuck on retrieving data from db.
The book has been using examples using PHP and MYSQL... which I do not know. I use a .net web server and SQL, so I'm trying to convert this example from the tutorial, to how I would do it on my .net webserver.
the result in JSON format should be something like this
{
"data"[
{
"id":1",
"text" : "menu1",
"items": [
{"id": 2",
"text: "submenu2
},
{
"id":"3",
"text":"submenu3"
}
the php code they give me is this
php file 1
$permissions = retrievePermissions($userName); $modules =
retrieveModules($permissions); $result = retrieveMenuOptions($modules,
$permissions);
php file 2
function retrievePermissions($userName){
require('../db/db.php');
$sqlQuery = "SELECT p.menu_id menuId FROM User u ";
$sqlQuery .= "INNER JOIN permissions p ON u.groups_id = p.groups_id ";
$sqlQuery .= "INNER JOIN menu m ON p.menu_id = m.id ";
$sqlQuery .= "WHERE u.username = '$userName' ";
$permissions = [];
if ($resultDb = $mysqli->query($sqlQuery)) {
while($user = $resultDb->fetch_assoc()) {
$permissions[] = $user['menuId'];
}
}
$resultDb->free();
$mysqli->close();
return $permissions; }
function retrieveModules($permissions){
require('../db/db.php');
$inClause = '(' . join(',',$permissions) . ')';
$sqlQuery = "SELECT id, text, iconCls FROM menu WHERE menu_id IS NULL AND id in $inClause";
$modules = [];
if ($resultDb = $mysqli->query($sqlQuery)) {
while($module = $resultDb->fetch_assoc()) {
$modules[] = $module;
}
}
$resultDb->free();
$mysqli->close();
return $modules; }
function retrieveMenuOptions($modules, $permissions){
require('../db/db.php');
$inClause = '(' . join(',',$permissions) . ')';
$result = [];
foreach ($modules as $module) {
$sqlQuery = "SELECT * FROM menu WHERE menu_id = '";
$sqlQuery .= $module['id'] ."' AND id in $inClause";
// check if have a child node
if ($resultDb = $mysqli->query($sqlQuery)) {
// determine number of rows result set
$count = $resultDb->num_rows;
if ($count > 0){
$module['items'] = array();
while ($item = $resultDb->fetch_assoc()) {
$module['items'][] = $item;
}
}
$result[] = $module;
}
}
$resultDb->close();
$mysqli->close();
return $result;
I'm trying to figure out how to return the same json format using my .net webservice/SQL instead of php/MySQL.
It seems like it does 3 separate functions. And the result array is used as a parameter for the next query.
The basics seem easy... like for retreivePermissions... it is a simple SELECT WHERE statement.
retrieveModules seems to be an INNER JOIN with the first results.
But the last one... retrieveMenuOptions, it pulls in both results as parameters, and It returns results.
That is what I don't understand... how can I pull the results from SQL in the same JSON result format.
Am I making sense?
I have an example that uses a .NET Web API controller. Not exactly a web service, but you'll get the idea. Check it out here: http://jorgeramon.me/2015/ext-js-grid-search-with-net-and-mysql-backend/

Refactor if statements in PHP or another solution for if statements (not switch case)

I have some if statements in my code.
e.g:
if($option[0]->posts == 1 && $option[0]->pages == 1){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND (post_type="page" OR post_type="post") ORDER BY post_title ASC', OBJECT );
}
if($option[0]->pages == 1 && $option[0]->posts == 0){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="page" ORDER BY post_title ASC', OBJECT );
}
if($option[0]->pages == 0 && $option[0]->posts == 1){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="post" ORDER BY post_title ASC', OBJECT );
}
a bit pseudo code of the code above:
if foo = 1 and bar = 1 -> return foo and bar
if foo = 0 and bar = 1 -> return only bar
if foo = 1 and bar = 0 -> return only foo
if foo = 0 and bar = 0 -> return false
You see:
00
10
01
11
00
If I insert another variable I'll get a lot of more opportunities and that is realy bad. Because I'll get realy big if statements.
Can somebody tells me another opportunitie to achive the same result?
Thank you.
I'd do it like this:
$sql_condition = '( 1=2 '; // one fake-condition, just to make it possible to start with 'OR' later
foreach($option[0] as $key => $value) { // iterate through all possible conditions
if($value===1) { // maybe exclude $keys that should not be used here
$sql_condition.=' OR post_type="'.$key.'"';
}
}
$sql_condition.=')';
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND '.$sql_condition.' ORDER BY post_title ASC', OBJECT );
Please try this code :
$sub_query = $operator = '';
if($option[0]->posts == 1)
{
$sub_query = 'post_type="page"';
$operator = ' OR';
}
if($option[0]->pages == 1)
{
$sub_query .= $operator.' post_type="post"';
}
if(empty($sub_query))
{
return false;
}
else
{
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND ('.$sub_query.') ORDER BY post_title ASC', OBJECT );
}
Create an array($arr) and set the key like "0,0" and value like "$sql";
and your code will be like this:
$tempKey = $option[0]->pages . "," . $option[0]->posts;
if(isset($arr[$tempKey]) {
$results = $wpdb->get_results($arr[$tempKey]);
}
So when you want to add more pages and posts all you will do is to change the arr.
$types = [];
if ($option[0]->posts)
$types[] = '"post"';
if ($option[0]->pages)
$types[] = '"page"';
if (!$types)
return null;
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND (post_type IN ('. implode(',', $types) .')) ORDER BY post_title ASC', OBJECT );

query with php array in mysql

I want to fetch contents with multiple filters, right now there's only one.
For Example:
SELECT * FROM Table1 WHERE status=true AND category = 'Camera' AND
model = 'Samsung' AND type = 'New'
I want to create an array for it. But as I'm a newbie in this one not getting a lead.
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter = 'AND cat_id=' . $filter;
}
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . $filter;
Any help will be appreciated.
This will get you closer to the solution, though it will not replace the cat_id in the query, which will certainly be wrong - though impossible to do too much more without the array structure:
function getAllRequests($filter)
{
$addfilter="";
if(!empty($filter))
{
foreach($filter as $val)
{
$addfilter. = ' AND cat_id=' . $val .'\'';
}
}
return $addFilter;
}
$myFilters=getAllRequests($filter);
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
On the other hand, if your array is strucutred in a way like this:
array{ category => camera, model => samsung); // etc
you could use the following:
function getAllRequests($filter)
{
$addfilter="";
if(!empty($filter))
{
foreach($filter as $key => $val)
{
$addfilter. = " AND `$key` = '$val'";
}
}
return $addFilter;
}
$myFilters=getAllRequests($filter);
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
Edit: You can loop through all the filters in the following manner:
function getAllRequests()
{
$addfilter="";
if(!empty($_REQUEST))
{
foreach($_REQUEST as $key => $val)
{
$addfilter. = " AND `$key` = '$val'";
}
}
return $addFilter;
}
$myFilters=getAllRequests();
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
You don't need to pass the $_REQUEST (which will work for both GET and POST) as it already a superglobal.
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter = 'AND cat_id=' . $filter;
}
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . $addfilter;
You can use another approach, which is using optional parameters and it will make your WHERE clause dynamic as you want. In this approach you pass all parameters' values directly to the sql query which should look like so:
SELECT *
FROM Table1
WHERE 1 = 1
AND (#status IS NULL OR status = #statusParam)
AND (#category IS NULL OR category = #categoryParam)
AND (#model IS NULL OR model = #modelParam)
AND (#type IS NULL OR type = #typeParam)
Then If any of the parameters #statusParam, #categoryParam, #modelParam or #typeParam passed to the query with NULL values, then the comparison with the column holding that value will be ignored. I used the predicate 1 = 1, in case all the values passed to the query with all NULL values in the case all the WHERE clause will be ignored as it won't presented, since WHERE 1 = 1 always true and it will be like SELECT * FROM Table1.
use this
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter .= 'AND cat_id=' . $filter;
}
return $addfilter;
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . getAllRequests($filter);
When you are sending array make sure it has indexes
$conditions = array('category' => 'Camera', 'model' => 'Samsung' , 'type' => 'New')
Now loop through it. in your else condition
foreach($conditions as $key =>$value){
$addfilter .= 'AND ' . $key . ' = ' . $value;
}

Rewrite manually created nested JSON to use PHPs built in functions

I have in my table records that are related one to another by a parentId field. When fetching them from the DB I need to create JSON array of objects where the child records are added to 'children' property of parent objects :
[{
//main object
children : [
{
//#1st level children object
children: [
{
//#2nd level children object
}
]
}
]
},
{
(...)
]
But if there are no records with parentId equal to current record, then this property shouldn't be added to the object.
Right now I'm building the JSON string manually :
//first get the parents
$q = 'SELECT * FROM table WHERE parentId = 0';
$r = mysql_query($q);
$x=1;
$nr = mysql_num_rows($r);
while($e = mysql_fetch_array($r)){
if($x==1){
echo '[ { ';
}
else{
echo ' { ';
}
if($e['leaf']==1){
$leaf = 'true';
} else {
$leaf = 'false';
}
echo '"EndDate" : "'.str_replace('T00:00:00','',$e['EndDate']).'",
"Id" : '.$e['Id'].',
"Name" : "'.$e['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e['BaselineStartDate']).'"';
if($leaf){
echo ',"leaf": '.$leaf.'';
}
childs($e['Id'], $x, $nr);
if($x<$nr){
echo ',';
}
$x++;
}
if($x>1){
echo ']';
}
function childs($id, $x, $nr, $x2='', $nr2=''){
//now see if there are childern
$q2 = 'SELECT * FROM table WHERE parentId = "'.$id.'" ';
$r2 = mysql_query($q2);
$nr2 = mysql_num_rows($r2);
if($nr2>0){
echo ',"children": [ ';
$x2 =1;
while($e2 = mysql_fetch_array($r2)){
if($e2['leaf']==1){
$leaf2 = 'true';
}
else{
$leaf2 = 'false';
}
echo '{
"EndDate" : "'.str_replace('T00:00:00','',$e2['EndDate']).'",
"Id" : '.$e2['Id'].',
"Name" : "'.$e2['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e2['BaselineStartDate']).'",
"leaf" : "'.$leaf2.'"';
childs($e2['Id'],$x,$nr,'',$x2,$nr2);
if($x2<$nr2){
echo ',';
}
$x2++;
}
echo '] }';
}
else{
echo ',"children" : []}';
}
}
Is there an easy way to make this code more robust using some built-in PHP features like fetch_assoc or something like that?
You should rather..
Fetch the results from the database
Reformat as per the requirement (related code you can use with some alteration PHP Create a Multidimensional Array from an array with relational data
Then finally, json_encode the resulting array

Categories