Comparing GET response to a variable - php

I'm having trouble comparing the value returned from a get request to a variable. The get returns in a format that includes the row in the databases name along with the value. Since the variable does not have that "tag" too they don't compare correctly. Is there a way to compare them properly?
{"email":"[value]"}
Thats the format its returning in.
The value is in an array.
$app->get('/api/user_info/{email}', function($request, $response) {
require_once('dbconnect.php');
$email = $request->getAttribute('email');
$query = "select email from user_info";
$result = $mysqli->query($query);
$count = 0;
while($row = $result->fetch_assoc()){
$data[] = $row;
}
for ($i=0; $i < count($data); $i++){
if($data[$i] == ($email)){
$newResponse = $response->withjson($data[$i]);
return $newResponse;
//Should return email if they're the same
}
else {
$count += 1;
}
if ($count == count($data)){
$newResponse = $response->withjson("Email not found");
return $newResponse;
}
}
});

json_decode( '{"email":"[value]"}' ) will give you a standard PHP object with an "email" property.
I'm guessing a bit as to what GET key to use, but this should help you figure it out:
$var = json_decode( $_GET['email'] );
echo $var->email;

Related

Check if all values in array are in database and store ones that aren't in new array [duplicate]

This question already has answers here:
Check if all values in an array exist in a database column
(2 answers)
Closed 1 year ago.
I have an array that looks something like this -> ["john.smith#gmail.com", "jane.doe#gmail.com", "jack.smith#gmail.com"]. I want to increment $count for each email that exists in the database. If it doesn't exist (invalid), then I want to push it to the $invalidEmails array.
After that, I want to set my $output according to whether all the emails in the original array are valid or not. They're valid if all of them exist in the database. I'd appreciate some help with this as I'm not sure how to go about it from here. It doesn't work for all cases right now, for example if first email is valid but second one is invalid.
This is what I have so far:
$result = $conn->query("SELECT mail FROM dej_colleagues");
$rows = mysqli_fetch_all($result, MYSQL_ASSOC);
$tags = preg_split("/\,/", $_POST['tags']);
$invalidEmails = array();
$count = 0;
for ($i = 0; $i < sizeof($tags); $i++) {
$trim_brackets = trim($tags[$i], '[]');
$trim_quotes = trim($trim_brackets, '"');
foreach($rows as $row) {
if ($trim_quotes == $row["mail"]) {
$count += 1;
break;
}
}
if ($count == 0) {
array_push($invalidEmails, $tags[$i]);
}
}
$output = array();
if (sizeof($tags) == $count) {
$output = array("validity => "valid emails");
}
else {
$output = array("validity" => "invalid emails", "emails" => $invalidEmails;
}
echo json_encode($output);
Your code seems convoluted, so rather than debug it I started with a more focussed query and worked from there.
Basically, the query asks the database for a list of emails that appear in your $tags array, then uses array_diff() to find any that appear in $tags, but not in the database.
From there you can produce your output directly.
ini_set('display_errors',1);
$mysqli = new mysqli('mysql.lv.local','userName', 'userPassword','schemaName' );
// Assuming the input is a string and not an array, json_decode it.
$tags = '["john.smith#gmail.com", "Jane.doe#gmail.com", "jack.smith#gmail.com","fred.jones#gmail.com"]';
$tags = json_decode($tags);
// switch everything to lower case
$tags = array_map('strtolower', $tags);
// Build and prepare a query with placeholders. Note conversion to lower case
$sql = 'select distinct lower(`mail`) from `emails` where lower(`mail`) in (?'.str_repeat(',?', count($tags)-1).')';
//echo $sql;
$stmt = $mysqli->prepare($sql);
// Bind the values from $tags to the query
$stmt->bind_param(str_repeat('s', count($tags)), ...$tags);
// Execute
$stmt->execute();
// Bind a variable for the result
$stmt->bind_result($email);
// Retrieve the emails in to $dbMails
$dbMails = [];
while ($stmt->fetch()) {
$dbMails[] = $email;
}
//var_dump($dbMails);
// Anything that's in $tags but not in $dbMails is invalid
$absentEmails = array_diff($tags, $dbMails);
//var_dump($absentEmails);
if ($absentEmails) {
$op= ["validity"=>"Invalid enails", 'emails'=>array_values($absentEmails)];
} else {
$op= ["validity"=>"Valid enails"];
}
echo json_encode($op);

PHP Inserting variables in array, but can't json_encode

Im with this for days, i tested if variables are being filled and they are, but i think somehow im not doing array right because 'echo json_encode($response)' is printing nothing. I also tried to replace variables in array to just random numbers and everything went fine, just with variables does work.
public function getPlaces() {
$places = array();
$stmt = "SELECT * FROM poi ";
$retval = mysqli_query( $this->conn, $stmt );
if ($retval) {
while($row=mysqli_fetch_array($retval)) {
$name = $row["name"];
$lat = $row["latitude"];
$lng = row["longitude"];
$desc = $row["descricao"];
$rating = $row["rating"];
$lm = $row["lm"];
$la = $row["la"];
$lv = $row["lv"];
$places[] = array('name'=> $name, 'lat'=> $lat, 'lng'=> $lng, 'desc'=> $desc, 'rating'=> $rating,
'lm'=> $lm, 'la'=> $la, 'lv'=> $lv);
}
return $places;
}else
return false;
}
The function is called here:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array("error" => FALSE);
$places = $db->getPlaces();
if ($places != false) {
$response["places"] = $places;
echo json_encode($response);
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Error";
echo json_encode($response);
}
Instead of using associative array, use mysqli_fetch_object() to get the result set as object. You do not have to type all the field names if you use array_push().
while($row=mysqli_fetch_object($retval)):
array_push($places, $row);
endwhile;
Vardump the $places array to check the array.
E.g.
vardump($places); die;
or
print_r($places); die;
Did you notice the $ is missing before the $row variable on that line ?
$lng = row["longitude"];
This kind of missed (bad handled) Notice + Warning won't make your array.
Notice also that if your array is filled with some type of value it won't json_encode. Especially NaN values (thinking of this because of the nature of some fields like "rating" that could result in a NaN value).
Try by steps :
Dump your result for one line only with a LIMIT 1 in your SQL query to see if it works. Try only with one field...
Notice that $places = [];
is more optimized than a
$places = array();
Same with
$places[] = ['name'=> $name, ... ];

PHP String in Array returns only first charachter

I have a php function to display a list of revslider's sliders (wp plugin), the string returns only the first letter of the sliders' names
here is my code :
function jobboard_revslider(){
if (class_exists('RevSlider')) {
$theslider = new RevSlider();
$arrSliders = $theslider->getArrSliders();
$arrA = array();
$arrT = array();
foreach($arrSliders as $slider){
$arrA[] = $slider->getAlias();
$arrT[] = $slider->getTitle();
}
if($arrA && $arrT){
$result = array_combine($arrA, $arrT);
}
else
{
$result = false;
}
return $result;
}
}
I tried all I know and other answers around here but no hope.
I would really appreciate a push !
Thanks
Check sizeof ($ array)> 0 do this for both arrays. Also just try to echo what you are getting in getalias and gettitle methods before storing it in array.
function jobboard_revslider(){
if (class_exists('RevSlider')) {
$theslider = new RevSlider();
$arrSliders = $theslider->getArrSliders();
$arrA = array();
$arrT = array();
foreach($arrSliders as $slider){
$arrA[] = substr($slider->getAlias(), 1);
$arrT[] = substr($slider->getTitle(), 1);
}
if($arrA && $arrT){
$result = array_combine($arrA, $arrT);
}
else
{
$result = false;
}
return $result;
}

Json wont response my array in php

I am trying to fetch multiple rows from my database and then encode them with json so I can access them in my Android application. I've successfully encoded an object but I couldn't find a way to do the same with an array. My code looks like:
if ($tag == 'friends') {
$id = $_POST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
$response[ "error"] = FALSE;
$result[] = array(
$response["friends"]["unique_id"] = $row["unique_id"],
$response["friends"]["name"] = $row["name"],
$response["friends"]["email"] = $row["email"]);
}
echo json_encode($response);
}
The code from getMyFriends($id) I have already tested and it works fine. It returns :
$result = mysql_fetch_array($result);
return $result;
When using a rest client passing the parameters:
Tag: friends
id: $id
this is the json response that I get:
{
"tag": "myfriends",
"error": false
}
, but no actual database data.
If anyone knows what I'm doing wrong, I'd really appreciate it, I've been browsing the internet for hours now.
If getMyFriends already have a $result = mysql_fetch_array($result);you don't need to fetch again.
You could simply:
$friends = $db->getMyFriends($id);
echo json_encode($friends);
But that will only return one friend, if you want all remove $result = mysql_fetch_array($result); from getMyFriends and return the pure mysql_result, then do something like:
$result = array();
while($row = mysql_fetch_assoc($friends)){
array_push($result,$row);
}
echo json_encode($result);
I tried this and it worked.
if($tag=='friends'){
$id = $_REQUEST['id'];
$friends = $db->getMyFriends($id);
if ($friends != false) {
// friends found
$result[] = array();
while($row = mysql_fetch_assoc($friends)){
$response[ "error"] = FALSE;
$result[] = array(
$response["friends"]["unique_id"] = $row["id"],
$response["friends"]["name"] = $row["name"],
$response["friends"]["email"] = $row["email"]
);
}
echo json_encode($result);
}
}

Return array of SQL results in php to be converted to JSON

I am trying to take a number of user entries from a SQL database and return it where it will be encoded to JSON and sent back to android.
Currently I am building the part to handle the results from querying the database:
$result = mysql_query("SELECT * FROM users WHERE tower='$tower'") or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
//if just one result return it
if ($resultNo == 1) {
// return result
return mysql_fetch_array($result);
//if more than one loop through
} else {
//add each row to an array
while($row = mysql_fetch_array($result)) {
$resultSet[] = $row;
}
return $resultSet[];
} else {
return false;
}
}
The code I am returning to is...
$result = $db->searchForPeople($tower);
Can I return either an array or a single result in this way or should I just add the single result to the array and return that?
Thanks for your help
can this way:
$resultSet['row'] = $row;
return json_encode($resultSet);
or for example:
function TEST()
{
$array=array();$i=0;
while($result=mysql_fetch_row(QUERY))
{
foreach ($result as $key=>$value){
if(!isset($array[$i])) $array[$i] = array();
$array[$i][$key] = $value;
}
$i++;
}
return $array;
}

Categories