I'm trying to get a parent category for a given sub category using the following function in PHP.
require_once("Connection.php");
$flag=true;
function get_parent_id($cat_id, $parent_id)
{
if ($parent_id==0)
{
return($cat_id);
}
else if ($flag==true)
{
$data1=mysql_query("select parent_id from category where cat_id=" + $cat_id);
while($row = mysql_fetch_assoc($data1))
{
$parent_id=$row['parent_id'];
}
$flag = false;
}
else if ($flag==false)
{
$data2=mysql_query("select cat_id from category where cat_id=" + $parent_id);
while($row = mysql_fetch_assoc($data2)) //The warning comes from here.
{
$cat_id=$row['cat_id'];
}
$flag = true;
}
$cat_id = get_parent_id($cat_id, $parent_id);
return($cat_id);
}
}
echo get_parent_id($ed_id, $parent_id); //Call the above function.
It always prompts the following warning.
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL
result resource in C:\wamp\www\zoom\Category.php on line 492
Even though there is no error in SQL. The included file Connection.php also works fine on all other pages. I didn't understand at all why this happens.
Strings are concatenated with ., not +.
String Operators
Related
I'm trying to build a permission/action control system for my users.
There are 3 tables:
appName_actions:
appName_roles:
appName_roles_members:
There are 2 functions that will obtain the relevant data:
$memRoleIDs = AccessControl::get_memberRoleIDs($appName);
$memActionIDs = AccessControl::get_memberActionIDs($appName, $memRoleIDs);
get_memberRoleIDs works fine, it targets member 327 and returns the desired '2,4'
That is then passed to get_memberActionIDs as '2,4'
It's at this point I'm having trouble working out how to return all the actionIDs in one variable/string.
get_memberActionIDs:
public static function get_memberActionIDs($appName = NULL, $memRoleIDs = NULL)
{
if($appName !== NULL && $memRoleIDs !== NULL)
{
$tbl = 'app_'.$appName.'_roles';
$memRoleID = explode(',',$memRoleIDs);
foreach($memRoleID as $value)
{
$db = openDB();
$sql = $db->prepare("SELECT actionIDs FROM $tbl WHERE roleID = '$value'");
if(!$sql->execute())
{
logThis('ERROR_crit' , 'Database Query Failed !!!' , 1 , __FILE__ , __LINE__);
die('<h2>There was a critical error and data has not been loaded correctly. Developers have been notified.</h2><h3>Please try reloading the page</h3>');
}
else
{
// sql executed ok - bind fetch results
$sql->bind_result($actionID);
$sql->fetch();
print $actionID.'<br>';
}
}// return all the actionIDs as 1 variable here
}
}// end func
Now with this, there is success up-to-a-point. It prints out the correct info:
1,2,3,4
5
And this is where I cannot go any further :(
I've looked into GROUP_CONCAT and CONCAT in the SELECT statement and .= in the PHP loop, but I just cannot figure this out.
I'd like to return this as '1,2,3,4,5' all in 1 string.
If you could point me in the right direction I would be very grateful :)
Instead of printing out separate results, create a single string and print after the loop exits. You say you've tried this but you didn't include the relevant code to check if the implementation is correct. Is this what you did?
public static function get_memberActionIDs($appName = NULL, $memRoleIDs = NULL)
{
if($appName !== NULL && $memRoleIDs !== NULL)
{
$tbl = 'app_'.$appName.'_roles';
$memRoleID = explode(',',$memRoleIDs);
$result = "";
foreach($memRoleID as $value)
{
$db = openDB();
$sql = $db->prepare("SELECT actionIDs FROM $tbl WHERE roleID = '$value'");
if(!$sql->execute())
{
logThis('ERROR_crit' , 'Database Query Failed !!!' , 1 , __FILE__ , __LINE__);
die('<h2>There was a critical error and data has not been loaded correctly. Developers have been notified.</h2><h3>Please try reloading the page</h3>');
}
else
{
// sql executed ok - bind fetch results
$sql->bind_result($actionID);
$sql->fetch();
$result .= $actionID;
}
}// return all the actionIDs as 1 variable here
print $result.'<br>';
}
}// end func
I am trying to add a product to my shopping cart.
I am getting an error saying:
Warning: Invalid argument supplied for foreach() in
It is telling me I am getting an error for the following code:
function isInCart($id) {
if (!empty($_SESSION['sess_uid']['cart'])) {
foreach ($_SESSION['sess_uid']['cart'] as $report) {
if ($report['reportID'] == $id) {
// Report ID found in Cart
return true;
}
}
// Looped through cart, ID not found
return false;
} else {
// Cart empty
return false;
}
}
The particular line from the above that is flagging the error is:
foreach ($_SESSION['sess_uid']['cart'] as $report) {
I am also getting the following error message:
Fatal error: Only variables can be passed by reference in
The code this relates to is the following:
function addToCart($id) {
$report = getReportByID($id);
$author = $report['userID'];
if (!empty($report)) {
// Got the report
if (!empty($_SESSION['sess_uid']['cart'])) {
if (!isInCart($id) && !isOwner($author) && !hasPurchased($id)) {
array_push($_SESSION['sess_uid']['cart'], $report);
return true;
} else {
return false;
}
} else {
$_SESSION['sess_uid']['cart'] = array();
if (!isInCart($id) && !isOwner($author) && !hasPurchased($id)) {
array_push($_SESSION['sess_uid']['cart'], $report);
return true;
} else {
return false;
}
}
} else {
// Unable to get report by ID
return false;
}
}
The particular line of code from the above that is flagging the error is:
array_push($_SESSION['sess_uid']['cart'], $report);
The code below is what gets my reports to populate the store
<?php
function getReportByID($id) {
$conn = new mysqli(localhost, root, DBPASS, DBNAME);
$sql = "SELECT * FROM reports WHERE reportID = '" . $conn->real_escape_string($id)."';";
// Performs the $sql query on the server
$report = $conn->query($sql);
return $report->fetch_array(MYSQLI_ASSOC);
}
?>
Any help would be greatly appreciated.
Thanks
i think this wil help:
it typcast your session as an array so even when the session is empty you dont get an error
foreach ((array)$_SESSION['sess_uid']['cart'] as $report) {
let me know if this fix the error?
This is the first time I learn class in PHP, I tried to make a simple search in database.
here is some script from my class:
class DB {
...
function list_query($query) {
$ns = array();
$q = mysqli_query($this->con_(), $query);
while($n = mysqli_fetch_assoc($q)) {
$ns[] = $n;
}
return $ns;
}
...
function num_query($q) {
$num = mysqli_num_rows($q);
return $num;
}
...
}
search script :
$key = "foo";
$qsearch = $db->list_query("SELECT * FROM posts WHERE content LIKE '%".$db->escape_query($key)."%'");
$num = $db->num_query($qsearch);
if ($num == 0) {
echo "<h2>not found</h2>";
} else {
echo "<h2>result for : ".$key."</h2>";
foreach($qsearch as $val) {
echo "<h4>".$val['title']."</h2>";
echo strip_tags($val['content']);
}
}
but there is an error with the num_query() function.
with warning :
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, array given in class/db.php on line 30.
I have checked it with manual mysqli_query() then use the num_query() function, it's work well.
sorry for my english
Your list_query() returns array. And your num_query expects mysqli_result as a parameter.
So, when you write $qsearch = $db->list_query(), you're getting an array; and then you pass that array to num_query.
Perhaps, your num_query should be like:
function num_query($result) {
return count($result);
}
this is taking me too long to figure out. I am using Codeigniter to query a database.
The model does this
function currentfunction($id)
{
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
return false;
}
}
The controller
$this->load->model('Display');
$results = $this->Display->currentfunction($id);
$this->load->view('current_items', array('currentitems' => $results));
The view
foreach($currentitems as $row){
echo $row['name']
///....do more
}
works just fine EXCEPT IF no rows are returned
then
Message: Invalid argument supplied for foreach()...
How do I handle the if...else...scenario
I tried this Q-A, but doesn't work for me. PlsHlp.
Just do:
if(is_array($currentitems)) {
foreach($currentitems as $row){
echo $row['name']
///....do more
}
}
else
{
echo "No items in database!";
}
You are getting an error because foreach expects its first argument to be an array. If there are no items in the database however your functions returns false.
This is because when you run your code:
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
return false;
}
when there are no rows returned the above code works fine it just doesnt work in the view where you try to run a for loop.
This for loop should not be run if there are no rows returned. yet you are trying to run a forloop even though there are no rows to work with.
My suggestion is changing the code like so:
$query = $this->db->get_where('mytable', array("id =" => $id));
if($query->num_rows() > 0){
return $query->result_array();
}else {
$noResults = true;
}
in the view you will have something like this before your for loop:
if($noResults != true){
foreach($currentitems as $row){
echo $row['name']
///....do more
}
}
else{
//do something
echo "No items in database!";
}
Hope this helps.
PK
Why don't you just do this:
function currentfunction($id)
{
return $this->db->get_where('mytable', array("id =" => $id));
}
In the view, if there are no results, an empty array will be returned and foreach won't throw an error:
foreach($currentitems->result_array() as $row)
{
echo $row['name']
///....do more
}
Much cleaner IMO.
If you want to show an error message in your view, you can do:
if($currentitems->num_rows() > 0)
{
foreach($currentitems->result_array() as $row)
{
echo $row['name']
///....do more
}
}
else
{
// Error message
}
This is better than checking if there are results with if/else twice, like halfdan and Pavan are suggesting.
How do i validate $_GET thats the number coming from correct source.
My url look like : index.php?page=items&catID=5
When users put something like 3 which is doesn't exist on catID. I want it to display error message.
$catID = intval($_GET["catID"]);
if($catID) {
$checkSQL = mysql_query("SELECT * FROM category WHERE category_type='2'");
while($checkROW = mysql_fetch_array($checkSQL)) {
$checkCAT != $checkROW["categoryID"];
echo "err msg";
}
This i can come up so far but it doesn't working as it fire error msg even in correct page.
Thank you
wallk makes a good point, there is a missing if. but if i read this correctly, wouldn't something along the lines of this be more what you are going for? Right now the line:
if($catID) {
is actually only checking if catID (or, catID from the $_GET) is non-zero (not false). My guess if you are looking to check if catID is the categoryID returned from SQL?
$catID = intval($_GET["catID"]);
checkcat($catID);
function checkcat($check_category) {
$checkSQL = mysql_query("SELECT * FROM category WHERE category_type='2'");
while($checkROW = mysql_fetch_array($checkSQL)) {
if ( $check_category != $checkROW["categoryID"] ) {
echo "err msg";
} else {
echo "not an error message";
}
}
}
Expounding on what you are looking for, how about something like this then?
$catID = ($_GET["catID");
if ( !is_numeric($catID) ) {
echo "Not a numeric category!"
} else {
$checkSQLQuery = "SELECT * FROM category WHERE categoryID = '{$catID}' AND category_type='2'"
$resultSQL = mysql_query($checkSQLQuery, $db);
/* NOTE!: Guessing on what your database resouce
pointer is - it isn't included in the origin snippet.
Although, the last opened should be used by default if
this is left out. */
if ( mysql_num_rows($resultSQL) < 1 ) {
echo "Error message, category ID not found"
} else {
echo "Found it!"
}
}
Oh, I see. The first line inside the while loop should have an "if":
while ($checkROW = mysql_fetch_array($checkSQL)) {
if ($checkCAT != $checkROW["categoryID"])
echo "err msg";
It looks like you'll be wanting to use mysql_fetch_assoc(), rather than mysql_fetch_array().