Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to send a string of numbers to the server and split each number. If the number exists on the database assign a "t" value and if it doesn't then assign "f" value.
But for some reason I get t's only.
<?php
# get phone from uid
include_once 'utils.php';
$phone = $_GET['phone'] or die("isRegistered: missing phone");
$response = "";
$phonearray = explode(":", $phone);
for ($i = 0; $i<sizeof($phonearray); $i++){
$result = findRow("phone", $phonearray[i], "user_device") or "true" ;
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."f".":";
$result = "";
}
}
die($response);
?>
There's actually a couple problems here.
As mentioned in the other answers, you're mistakenly using 't' in both branches of your code.
You appear to be using the string "true" instead of the boolean true. While it may appear to work because of the way PHP converts values between types, you're probably actually intending to use true, and using the string instead can lead to unexpected behavior later.
I don't know what findRow() does, but by adding or true (or even or "true") to the end of it, $result will always be true.
You're using i to reference the $phonearray instead of $i. i will generate a PHP warning, and will be interpreted as "i" - instead of the value of the $i variable.
If you look at this part of your code:
$result = findRow("phone", $phonearray[i], "user_device") or "true" ;
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."t".":";
$result = "";
}
You'll get better results by rewriting it like this:
$result = findRow("phone", $phonearray[$i], "user_device");
$response .= ($result ? 't' : 'f') . ':';
I'm guessing a bit as to what findRow() does since you didn't include anything about it - but I'm assuming it just returns a true/false value.
You'll notice that I've also simplified the entire if/else statement down to a couple lines by using the ternary operator as well.
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."t".":";
$result = "";
}
change this part to
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."f".":";
$result = "";
}
You have set "t" for both if and else condition.
and do check
if(isset($_GET['phone']))
if($result == "true")
{
$response = $response."t".":";
$result = "";
}
else
{
$response = $response."t".":";
$result = "";
}
change this part to
if($result == 'true')
{
$response = $response.'t:';
$result = '';
}
else
{
$response = $response.'f:';
$result = '';
}
Related
this is my code I want to convert this query in to a common query
if ($limit == 0) {
$response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->get();
} else {
$response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->limit($limit)->get();
}
You can save the query in a variable above the if/else statement. So something like this would work. Now if this is not the answer you are looking for please specify what you mean by common query!
$query = WebhookErrorNotification::where('is_error', true)->orderByDesc('id');
if ($limit == 0) {
$response = $query->get();
} else {
$response = $query->limit($limit)->get();
}
you can do something like this
$response = WebhookErrorNotification::where('is_error', true)
->when($limit !== 0, function ($query) use ($limit) {
$query->limit($limit);
})->orderByDesc('id')->get();
This is just a slight update from a question that was solved at an earlier date. I am simply trying to get 2 city names into variables from 2 different JSON results. This works good but every now and then one or the both sometimes returns nothing yet nothing changes?
Am I doing something wrong or is there a way to loop it until I get the result?
Sorry to be a pain but I really cannot see why its hit and miss?
The working code in PHP that runs the 2 queries and gets the result sometimes!
$p_lat = "52.406822";
$p_lng = "-1.519693";
$d_lat = "50.87626460000001";
$d_lng = "-0.3717470999999932";
$county = "";
$town = "";
$d_county = "";
$d_town = "";
$result = #file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=".$p_lat.",".$p_lng."&sensor=true" );
if ($result === FALSE) {
//manage exception from file_get_contents call
} else {
$geocodedinfo = json_decode($result);
if ($geocodedinfo->status == "OK") {
$county = "";
$town = "";
foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
if ( $addrcomps->types[0] == 'postal_town')
$town = $addrcomps->long_name;
}
}
}
$result = #file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=".$d_lat.",".$d_lng."&sensor=true" );
if ($result === FALSE) {
//manage exception from file_get_contents call
} else {
$geocodedinfo = json_decode($result);
if ($geocodedinfo->status == "OK") {
$county = "";
$d_town = "";
foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
if ( $addrcomps->types[0] == 'postal_town')
$d_town = $addrcomps->long_name;
}
}
}
echo $town;
echo "<br>";
echo $d_town;
It is fixed. I had to add HTTPS to it and include a KEY. I did not to start with as it was working without one!! Oh well.
$result = #file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=".$p_lat.",".$p_lng."&sensor=true&key=KEYHERE&" );
Thanks anyway
When I tried to print $result:
$result = #file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=".$p_lat.",".$p_lng."&sensor=true" );
echo "<pre>";
print_r(json_decode($result));
exit;
Below is the response:
stdClass Object
(
[error_message] => You have exceeded your daily request quota for this API. We recommend registering for a key at the Google Developers Console: https://console.developers.google.com/apis/credentials?project=_
[results] => Array
(
)
[status] => OVER_QUERY_LIMIT
)
So try to register your application first. Which will ultimately solve your problem.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new at php and I am not sure what I am doing wrong. I am trying to list all the records from a txt file. However, my code is only displaying the first line. How can I get the code to display all the records from the file?
$count = 0;
$soldOut = 0;
$eventFile = fopen("performances.txt", "r");
$event = fgets($eventFile);
while ( feof($eventFile));
{
list ($dateEvent, $performer, $ticketprice, $status) = explode(":", $event);
if($status == "Yes")
{
$status = "Tickets are still available";
$count = $status +1;
}
else
{
$status = "***SOLD OUT***";
$soldOut = $status +1;
}
print("<tr><td>$dateEvent </td>");
print("<td>$performer </td>");
print("<td>$ticketprice </td>");
print("<td>$status</td></tr>");
$event = fgets($eventFile);
}
Pay attention to the docs, you'll notice that your loop should be:
while( !feof($eventFile)) {
$event = fgets($eventFile); // THIS is where you get the current line
// do stuff here
}
you can read file this way. You can find more on this http://us1.php.net/function.file-get-contents
<?php
$data = file_get_contents("performances.txt",FILE_USE_INCLUDE_PATH); //read the file
$convert = explode(":", $data); //create array separate by new line
for ($i=0;$i<count($convert);$i++)
{
echo $convert[$i].', '; //write value by index
}
?>
Looping as instructed at http://www.php.net/manual/en/function.fgets.php
Basically, keep looping until fgets nolonger returns anything, and then check if pointer matches with end of file.
I also suggest you take a look at http://www.php.net/manual/en/function.stream-get-line.php
the comments make a case for performance gains.
$count = $soldOut = 0;
$eventFile = fopen("performances.txt", "r");
if ($eventFile) {
# Keep reading as long as fgets returns content
while ( ($event = fgets($eventFile)) !== false ) {
list ($dateEvent, $performer, $ticketprice, $status) = explode(":", $event);
if($status == "Yes") {
$status = "Tickets are still available";
++$count; # increase count with one
} else {
$status = "***SOLD OUT***";
++$soldOut; # increase soldout with one
}
echo '<tr>',
'<td>',$dateEvent,'</td>',
'<td>',$performer,'</td>',
'<td>',$ticketprice,'</td>',
'<td>',$status,'</td>',
'</tr>';
}
# something went wrong
if (!feof($eventFile)) {
echo "Error: unexpected fgets() fail\n";
}
# remember to close them files
fclose($eventFile);
} else {
# failed to open
}
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 can't find anything wrong with this... This should work right?
function ConfirmedNumber()
{
$rs = mysql_query("CALL ConfirmedNumber('" , $_SESSION['UserID'] . "',#Active)");
while ($row = mysql_fetch_assoc($rs))
{
if ($row['Active'] = 1)
{
return true;
}
}
return false;
}
Assuming the Stored procedure returns a single row with the value '1' in it then I can call the function like this right?
if (ConfirmedNumber())
{
//do some stuff.
}
To expand on my comment:
if ($row['Active'] = 1) should be if ($row['Active'] == 1) to work correctly.
If you want to avoid accidentally doing this in future, you could write your if statements like this:
if (1 == $row['Active'])
This way, you can't accidentally use = as PHP will throw a Fatal Error. You can read more about Comparison Operators at PHP.net
Comment below with the full answer:
The call to the stored proc... line $rs = mysql_query("CALL ConfirmedNumber('" . $_SESSION['UserID'] . "',#Active)"); had a comma instead of the period in the initial post.
you forgot your operator in your IF statement. Change it to this:
if ($row['Active'] == 1)
or even shorter
if ($row['Active'])
it can be something like this
function ConfirmedNumber($id)
{
$rs = mysql_query("CALL ConfirmedNumber('" . $id . "',#Active)");
while ($row = mysql_fetch_assoc($rs))
{
if ($row['Active'] == 1)
{
return true;
}
}
return false;
}
ConfirmedNumber($_SESSION['UserID']);