i tried below code to fetch results of column dpaid_status from mysql database & its working fine:
Database
site
$i = 0;
foreach($order as $orderData)
{
$k = 0;
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
while ($k < count($orderitemsarray))
{
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(":dorder_id" => $orderData['entity_id']));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
$dorderStatus = $roworders['dpaid_status'];
$productdetail = Mage::getModel('catalog/product')->load($orderitemsarray[$k]);
$designer_id = $productdetail->getDesignerID() ;
if($accountType == "admin")
{
$designerName = getDesignerName($productdetail->getDesignerID()) . " -(" . $productdetail->getDesignerID() . ")";
$stmt1 = $user_home->runQuery("SELECT * FROM order_details WHERE dproduct_id=:pid and designerorder_id=:doid");
$stmt1->execute(array(
":doid" => $orderData->getIncrementId(),
":pid" => $orderitemsarray[$k],
));
$paid_status='';
while($datas = $stmt1->fetch())
{
$paid_status=$datas['dpaid_status'];
}
$responce[] = array(
$paid_status
);
return json_encode($responce);
But for some columns there is no value for dpaid_status, so i wanted to display none for those in page. so instead of $paid_status=$datas['dpaid_status']; i tried below code ,
if ($roworders['dorder_id'] == '')
{
$paid_status='unpaid';
}
else
{
$paid_status=$datas['dpaid_status'];
}
ex : in above image there is no row for "15585" in database , so it should display unpaid for that.... but now its displaying blank....
You should check your $paid_status variable right before returning/using it. This way you will catch all cases when the value is empty (either empty value in the table or missing row in the database table).
I have added the new lines to your code, below:
$stmt1 = $user_home->runQuery("SELECT * FROM order_details WHERE dproduct_id=:pid and designerorder_id=:doid");
$stmt1->execute(array(
":doid" => $orderData->getIncrementId(),
":pid" => $orderitemsarray[$k],
));
$paid_status='';
while($datas = $stmt1->fetch())
{
$paid_status=$datas['dpaid_status'];
}
//added new lines of code here - START
if ( $paid_status == ''){
$paid_status='unpaid';
}
//added new lines of code here - END
$responce[] = array(
$paid_status
);
You can solve the problem also at SQL level, just using a query like:
SELECT [field_list], IFNULL(dpaid_status, 'unpaid') as paid_status FROM order_details
which return the dpaid_status value if the field is not null, else return 'unpaid'
You just need to use PHP empty().
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
so your if statement can be written
if (empty($roworders['dpaid_status']))
{
$paid_status='unpaid';
}
else
{
$paid_status=$datas['dpaid_status'];
}
if ($roworders['dpaid_status'] != '')
{
$paid_status=$datas['dpaid_status'];
}
else
{
$paid_status='unpaid';
}
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'm making a script to insert/update data from a mysql database to a postgres database.
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$postgres = "SELECT * FROM res_partner";
echo $postgres . "\n";
$pgresult = pg_query($db,$postgres);
$a = 0;
if(pg_num_rows($pgresult) > 0)
{
while($pgrow = pg_fetch_assoc($pgresult))
{
if($pgrow["id"] == $row["customer_id"])
{
$a + 1;
}
else
{
$a + 0;
}
}
var_dump($pgrow);
exit();
I want to check if the id in mysql database is also in the postgres database.
But the $pgrow returns "bool(false)" with my var_dump.
I have no idea why.
Because the var_dump() is outside the while loop.
The loop will continue to call pg_fetch_assoc until it returns false
Place the call inside the loop to see the contents of the current row:
while($pgrow = pg_fetch_assoc($pgresult))
{
if($pgrow["id"] == $row["customer_id"])
{
$a + 1;
}
else
{
$a + 0;
}
var_dump($pgrow);
}
Or use a proper debugger like XDebug to avoid having to write code like this
Can't you just do something like SELECT true FROM res_partner WHERE id = $customer_id so as not to do the while loop?
Then you would get either one row with a single value true if it exists, or false because no rows were returned.
I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}
I have a form that contains a number of textboxes i.e. Volome, Gain, Treble, Middle and Bass. Only whole numbers can be entered, which is validated with javascript and the Maxlength is set to, so no problem there. But how do I make sure that only numbers between 0 and 65535 are entered.
<?php
$name = $_POST['ampMod'];
$volume = 'Volume = '. $_POST['volume'];
$gain = 'Gain = '. $_POST['gain'];
$treble = 'Treble = '. $_POST['treble'];
$middle = 'Middle = '. $_POST['middle'];
$bass = 'Bass = '. $_POST['bass'];
if($volume != null && $gain != null && $treble != null && $middle != null && $bass != null)
{
echo "<h3> $name </h3>";
echo "<table><tr>";
echo "<td>$volume</td>";
echo "<td>$gain</td>";
echo "<td>$treble</td>";
echo "<td>$middle</td>";
echo "<td>$bass</td>";
}
else
{echo ("Please try again. Values must be between 0-65535. 0=Off 65535=Full On 10<br>Click here to try again!");}
?>
It is important to mention that your $volume, $gain, $treble, $middle and $bass will never actually be null as you have assigned a string to them in addition to the $_POST value. In addition you should always check if the $_POST values exist before trying to use them (or you will get an undefined notice message).
Here is an example for a PHP version based on the code you had (untested, but should work fine).
<?php
function isValidRange( $value, $low = 0, $high = 65535) {
// validate / cast value as int (add additional validation here
$value = (int)$value;
if ( $value > $high || $value < $low ) {
// return null (not a valid value)
return null;
}
// otherwise the value is valid so return it
return $value;
}
// make sure the $name var is safe to use
$name = ( isset($_POST['ampMod']) ) ? htmlentities($_POST['ampMod'],ENT_QUOTES,'UTF-8') : null;
$volume = ( isset($_POST['volume']) ) ? isValidRange($_POST['volume']) : null;
$gain = ( isset($_POST['gain']) ) ? isValidRange($_POST['gain']) : null;
$treble = ( isset($_POST['treble']) ) ? isValidRange($_POST['treble']) : null;
$middle = ( isset($_POST['middle']) ) ? isValidRange($_POST['middle']) : null;
$bass = ( isset($_POST['bass']) ) ? isValidRange($_POST['bass']) : null;
if( isset($volume) && isset($gain) && isset($treble) && isset($middle) && isset($bass) )
{
echo "<h3> $name </h3>";
echo "<table><tr>";
echo "<td>Volume = $volume</td>";
echo "<td>Gain = $gain</td>";
echo "<td>Treble = $treble</td>";
echo "<td>Middle = $middle</td>";
echo "<td>Bass = $bass</td>";
echo "</tr></table>";
} else {
echo ("Please try again. Values must be between 0-65535. 0=Off 65535=Full On 10<br>Click here to try again!");}
?>
Lastly I would not recommend just relying on JavaScript to actually check if your values are safe to use (i.e. echo them out), but using js as a pre-warning to users and then properly validating with PHP is the best way to go.
Just do something like this? Don't know why you would want to go between 0 and 65535. I doubt you want them to go that high. If you do just change 10 to 65535
if($value > 10 || $value < 0)
{
echo "Value cant be higher then 10 or lower then 0";
}
This makes sure the value is between 10 and 0
In situations like this, I often prefer to silently clean the form input. You've got client-side validation in place already. If the value is higher than allowed, just set the value to the maximum allowed instead of showing an error message.
// Clean the posted data and prevent notices if not set
$volume = (isset($_POST['volume'])) ? (int) $_POST['volume'] : 0;
// Make sure the value is within a certain range
$min = 0;
$max = 10;
$volume = min($max, max($min, $volume));
You can make use of the filter extension (bundled by default since 5.2):
$FILTER_VALIDATE_KNOB = array(
'filter' => FILTER_VALIDATE_INT,
'options' => array(
'min_range' => 0,
'max_range' => 65535,
)
);
$res = filter_input_array(INPUT_POST, array(
'ampMod' => $FILTER_VALIDATE_KNOB,
'volume' => $FILTER_VALIDATE_KNOB,
'gain' => $FILTER_VALIDATE_KNOB,
'treble' => $FILTER_VALIDATE_KNOB,
'middle' => $FILTER_VALIDATE_KNOB,
'bass' => $FILTER_VALIDATE_KNOB,
));
if (is_null($res) || in_array(null, $res, true)) {
// some or all fields are missing
// - missing fields have null value
} elseif (in_array(false, $res, true)) {
// some or all fields have a wrong value
// - wrong values have false value
}
I would do it with javascript. That way, you wouldn't have to submit the form and if the user types a higher number the alert (or something nicer) is shown:
In the input field, just call the javascript function:
<input id="thefirstnumbervalue" type="text" onchange="checknumber('thefirstnumbervalue')" />
<input id="thesecondnumbervalue" type="text" onchange="checknumber('thesecondnumbervalue')" />
In the function:
function checknumber(theid){
var mynumbervalue = document.getElementById(theid).value;
if (mynumbervalue > 65535){
document.getElementById(theid).value = "65535";
alert("Please try again. Values must be between 0-65535. ...");
}
if(mynumbervalue < 0){
document.getElementById(theid).value = "0";
alert("Please try again. Values must be between 0-65535 ...");
}
}
This is a simple approach in raw javascript. If you use ajax and jquery the result could be easier and nicer. This is complementary to the php solution, as you should also check the data before inserting in your database.
my code-
function create_id()
{
//global $myusername;
$part1 = substr("Piyush", 0, -4);
$part2 = rand (99,99999);
$part3 = date("s");
return $part1.$part2.$part3;
}
echo create_id(); //this is printing fine.
function isUniqueUserID($userIDToCheck)
{
$sqlcheck = "Select * FROM ruser WHERE userId='$userIDToCheck';";
$resource = mysql_query($sqlcheck)or die(mysql_error());
$count = mysql_fetch_assoc($resource);
if( count($count) > 0)
{return false;}
return true;
}
$userIDVerifiedUnique = false;
while(! $userIDVerifiedUnique )
{
$userIDToCheck = create_id();
$userIDVerifiedUnique = isUniqueUserID($userIDToCheck );
}
loop is just going on and on from while loop to function IsUniqueUser() and vice versa.????
If there are no rows returned from the MySQL query (i.e. the $userIDToCheck is not in the table, it is unique) then mysql_fetch_assoc will return FALSE. When that happens, count(FALSE) returns 1 (one)! Since that value is greater than zero the function returns FALSE.
In short, if there is a row returned (the string is not unique) your isUniqueUserID function returns FALSE; if there is no row returned (the string is unique) it still returns FALSE.
A simple, new, function to check on the database table could look something like the following...
function isUniqueUserID($userIDToCheck)
{
$userIDToCheck = mysql_real_escape_string($userIDToCheck); // Assume not already escaped
$sqlcheck = "SELECT 1 FROM ruser WHERE userId='$userIDToCheck' LIMIT 1";
$resource = mysql_query($sqlcheck) or die(mysql_error());
return (bool) mysql_num_rows($resource);
}
First, try changing your isUniqueUserID() function to this
function isUniqueUserID($userIDToCheck)
{
$userIDToCheck = mysql_real_escape_string($userIDToCheck); //prevent SQL injection
$sqlcheck = "Select userId FROM ruser WHERE userId='$userIDToCheck';";
$resource = mysql_query($sqlcheck)or die(mysql_error());
$count = mysql_num_rows($resource);
return ($count > 0) ? false : true;
There's no point in returning an associative array just to count the number of rows in it. And there's no point in doing a SELECT * when counting just do SELECT userId since that's all you're concerned with.
I don't see any other reason that isUniqueUserID() would return false unless your ruser table has every possible ID.