pg_fetch_assoc returns boolean - php

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.

Related

Check for empty rowset in oci_fetch_array

I am doing the following...
$approved = oci_parse($conn_prs, "select * from patch_files where patch_reviewer = '". $_SESSION['id'] ."' and patch_status = 'Approved'"); // now rows available for current id
oci_execute($approved);
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS )) {
var_dump($row); // shows nothing
if ($row == null) { echo "<p>None Found...</p>"; }
else { ....
Not sure why the null condition is not working...
Your null condition is not working because $row is never null. oci_fetch_array() returns an array of the row fields, or false. If there are no rows your while loop is not executed.
You seem to have misunderstood the purpose of OCI_RETURN_NULLS. When used, it creates array elements for empty fields in $row, not an empty array if there are no rows.
A quick and dirty way to do what you want is:
$i = 0;
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS)) {
$i++;
...
}
if ($i == 0) {
echo "<p>None Found...</p>";
}
try with -
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS )) {
var_dump($row); // shows nothing
if (empty($row)) { echo "<p>None Found...</p>"; }
else { ....
oci_fetch_array() - returns the next row from a query as an array.

GET Multiple MySQL Rows, Form PHP Variables, and Put Into Json Encoded Array

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']);
}

Loop until returned true with PHP

I'm generating a random code, and I need to check to be sure that the code isn't already in the database. I'm assuming this requires some type of a loop. I have my query all setup and I need it to run a block of code again if mysql_num_rows == 0.
Use a do...while loop:
do {
// Your logic
} while (condition);
$key = true;
while($key){
// Do stuff
if(mysql_num_rows($result) > 0) $key = false;
}
Simple upgrade of James L. script - loop script for test if exist login ID in database. If exist, will add +1 after login:
$key = true;
$a = 1;
$login_test_origin=$login_test;
while($key){
$query_test="SELECT count(*) as 'all' FROM user WHERE login='$login_test'";
$row_test=mysql_fetch_array(mysql_query($query_test));
$error=$row_test[all];
if($error > 0) {
$key = true;
$login_test=$login_test_origin.$a;
$a++;
}
else {
$key = false;
$login=$login_test;
}
}
echo"Used login ID: $login";
Here is a quite different route:
while(true){
if(/* Your logic which you expect to be true */){
break;
}
}

never ending loop : fatal error

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.

How to check if results on while($row = mysql_fetch_array in PHP

Im trying to figure out how to handle this is no results are returned, how would I code that?
while($row = mysql_fetch_array($Result))
So like if there a results: print them out
else: show a link
http://ca3.php.net/manual/en/function.mysql-num-rows.php
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) { ... }
} else {
// show link
}
You can use mysql_num_rows() to tell you how many results are found. Using that with a simple if-statement, and you can determine what action to take.
if (mysql_num_rows($result) > 0) {
// do while loop
} else {
// show link
}
Others suggest using mysql_num_rows() but you should be aware that that function works only if you use a buffered query. If you query using mysql_unbuffered_query(), the number of rows in the result is not available.
I would use a simple flag variable:
$found_row = false;
while ($row = mysql_fetch_array($result)) {
$found_row = true;
. . .
}
if ($found_row == false) {
// show link
}
It may seem redundant to set $found_row to true repeatedly, but assigning a literal value to a variable ought to be an insignificant expense in any language. Certainly it is small compared to fetching and processing an SQL query result.
Use even shorter syntax without insignificant mysql_num_rows to save processor time:
if($result) {
// return db results
} else {
// no result
}
I might have figured it out:
if (!($row = mysql_fetch_array($descResult)))
{
echo "<tr><td>Add Link</td></tr>";
}
This can be done without mysql_num_rows() or an additional (flag) variable
if ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo 'no rows in result set';
}
else {
do {
echo $row['X'];
} while ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) );
}
but it duplicates the actual fetch command (one in the if-statement and one in the while-clause).

Categories