Hi I am creating an android app and made a fetch API that can get the converted json data
Here's my code
lib.php
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$userRows = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
and on my fetch_api.php
<?php
require_once '../database/database.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// edittext from android
$username = $_POST['username'];
$arr = array();
if($user->fetchUserData($username))
{
$arr['success'] = 1;
$arr['message'] = "Success fetching data";
echo json_encode($arr);
}
else
{
$arr['success'] = 0;
$arr['message'] = "Failed fetching data";
echo json_encode($arr);
}
}
?>
Right now I can successfully get the
{
"success": 1,
"message": "Success fetching data"
}
Now I want to display all of my data like fullname, address, phonenumber etc to be displayed .
When I am trying to do it like this
lib.php
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$userRows = $stmt->fetch(PDO::FETCH_ASSOC);
if($userRows)
{
$response["success"] = 1;
$response["message"] = "User Profile";
$response["user"] = array();
foreach($userRows as $rows)
{
$user = array();
$user["username"] = $rows['username'];
$user["fullname"] = $rows['fullname'];
array_push($response["user"], $user);
}
echo json_encode($response);
}
else
{
$response["success"] = 0;
$response["message"] = "Failed Fetching";
die(json_encode($response));
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
It's giving me the error saying
illegal string offset warning on username and fullname
I hope I am clear on my problem . Please ask me if my question is not clear so I can edit my question . Thank you.
ADDED
when I directly use json_encode like this
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$userRows = $stmt->fetch(PDO::FETCH_ASSOC);
json_encode($userRows);
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
it gives me this result
{"success":0,"message":"Failed fetching data"}
As I understand the problem that you are facing is how to return rows from the class methods, when it should only return true on success and false on fail.
You got something like that:
<?php
class user{
...
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$userRows = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
...
}
?>
You need to add a public property like $userRows to it and assign that property with your method:
class user{
public $userRows; // added here
...
public function fetchUserData($username)
{
try
{
$stmt = $this->db->prepare("SELECT * FROM user_profile WHERE username=:username");
$stmt->execute(array(':username' => $username));
$this->userRows = $stmt->fetch(PDO::FETCH_ASSOC); // changed here
And after that you can:
<?php
...
if($user->fetchUserData($username)){
echo json_encode($user->userRows);
}else{
echo "error occured";
}
Hopefully it helped.
Related
Hi I get the "There is no active transaction" when I run my code below:
public function Login($username, $password)
{
try
{
$database = db_camagru();
$query = "SELECT id FROM users WHERE (username=:username OR email=:username) AND password=:password";
$database->exec($query);
$database->commit();
if ($query->rowCount() > 0)
{
$result = $query->fetch(PDO::FETCH_OBJ);
return $result->id;
}
else
{
return false;
}
}
catch (PDOException $e)
{
exit($e->getMessage() . "kwezi");
}
}
the error seems to be coming from my $database->commit(); line.
here is my code for optverify.php if the input number is wrong its redirect to index.php its not giving error.its should give a error for wrong otp but please help me to solve this issue
<?php
// Create a unique instance of your session variables
session_start();
if(isset($_SESSION['usr_id']))
{
$uid=$_SESSION['usr_id'];
} else {
header("Location:login.php");
}
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
if (isset($_POST['verifyotp'])) {
$otpsms = $_POST['smsotp'];
$otpemail = $_POST['emailotp'];
$user = $db->verifyotp($uid);
if($user){
$user['smsotp'] = $otpsms;
$user['emailotp'] = $otpemail;
header("Location:index.php");
} else {
$errormsg = "Invalid otp";
}
}
?>
and my codes for data base function are below
public function verifyotp($uid){
$stmt = $this->con->prepare("SELECT uid,smsotp,emailotp FROM users WHERE uid = '$uid'");
$stmt->bind_param("i", $uid);
if ($stmt->execute()) {
$stmt->bind_result($uid,$smsotp,$emailotp);
$stmt->fetch();
$user = array();
$user["uid"] = $uid;
$user["smsotp"] = $smsotp;
$user["emailotp"] = $emailotp;
$stmt->close();
return $user;
} else
{
return $stmt;
}
}
Not tested but this should work !! Let me know if this doesn't work. will delete this answer.
Updated
Change this $user = $db->verifyotp($uid); to $user = $db->verifyotp($uid, $otpsms, $otpemail);
then modify your function like below if you are willing to test 3 parameters (1) id (2) smsotp (3) emailotp.
public function verifyotp($uid, $sotp, $eotp){
$stmt = $this->con->prepare("SELECT uid,smsotp,emailotp FROM users WHERE uid = '$uid' And smsotp='$sotp' And emailotp ='$eotp'");
$stmt->bind_param("i", $uid);
if ($stmt->execute()) {
$stmt->bind_result($uid,$smsotp,$emailotp);
$stmt->fetch();
$user = array();
$user["uid"] = $uid;
$user["smsotp"] = $smsotp;
$user["emailotp"] = $emailotp;
$stmt->close();
return $user;
} else
{
return $stmt;
}
}
I am working on an app that needs to select data from a MySQL database. I am currently testing the PHP script via my browser to make sure that it is returning the correct data. The issue is currently it returns the exception "Database Error!". I have included my PHP script.
get_agencies_by_city.php
<?php
/*
* Following code will get all agencies matching the query
* Returns essential details
* An agency is identified by agency id
*/
require("DB_Link.php");
$city = ($_GET['City']);
//query database for matching agency
$query = "SELECT * FROM agency WHERE City = $city";
//Execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//Retrieve all found rows and add to array
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Agency found!";
die(json_encode($response));
}
?>
Here is the DB_Link.php
<?php
// These variables define the connection information the MySQL database
// set connection...
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
You should rewrite your query to this, as it is a prepared statement and your query will be much safer (and working)!
//your code
try {
$statement = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$statement->execute(array('city' => $city));
// rest of your code
}
// and the exception
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
also you should check if $_GET really is set!
LIKE THIS:
try {
$stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$stmt->execute(array('city' => $city));
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} }
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
The variable $city needs to be in your query. Do something like this:
$query = "SELECT * FROM Agency WHERE City = " . $city;
I have integrated google loing to my website. It's working fantastic. When someone logs in via google for the firs time, then a new entry is stored in the database.
But, when he logs in again..only the last login (a column on the table) should be updated...but instead, mysql adds a new row.
What am I doing wrong here?
public function trigger_registration_from_google($fname,$lname,$email)
{
global $conn;
try
{
if(useremailexists($email))
{
$date = date('Y-m-d');
//run update query
//user already exists, only update
try
{
$s = $conn->prepare("UPDATE users set last_login = :last_login where emailid = :email ");
$s->bindParam(':last_login',$date);
$s->bindParam(':email',$email);
$s->execute();
$s->closeCursor();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
else
{
//insert
//insert now..since he is a new user
$date = date('Y-m-d');
$v=1;
$r="google";
try
{
$s = $conn->prepare("INSERT INTO users(fname,lname,emailid,registeredby,registeredon,last_login,verified) values (:fname,:lname,:emailid,:registeredby,:registeredon,:last_login,:verified)");
$s->bindParam(':fname',$fname);
$s->bindParam(':lname',$lname);
$s->bindParam(':emailid',$email);
$s->bindParam(':registeredby',$r);
$s->bindParam(':registeredon',$date);
$s->bindParam(':last_login',$date);
$s->bindParam(':verified',$v);
$s->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Edit
useremailexists
function useremailexists($email)
{
//check if the email exists
global $conn;
try
{
$s = $conn->prepare("SELECT * from users where emailid = :email");
$s->bindParam(':email',$email);
$s->execute();
if($s->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Validate if the function useremailexist return true or false , we can't help you without this piece of code.
I am using luracast restler for making REST APIs. I am trying to update user using post method. But my sql is not executed and i dont know how to look for sql errors in json format.
My API code is
<?php
class User
{
public $dp;
function __construct()
{
$this->dp = new DB_PDO_MySQL();
}
function post($request_data = NULL)
{
$response = array();
if(array_key_exists('user_id', $request_data)){
$response = $this->dp->updateUser($request_data);
}else{
$response = $this->dp->signUp($request_data);
}
return $response;
}
}
and updateUser function in MySQL is as
function updateUser($postData){
$response = "";
$data = array();
if($this->checkToken($postData['token'])){
$sql = $this->db->prepare('SELECT * FROM phpclassifieds_acc_users WHERE username = :username');
$sql->execute(array(':username' => $postData['username']));
if($sql->rowCount()>0)
{
return $this->response(0,'','The Username ('.$postData[username].') is already in use');
}
$sql = $this->db->prepare('SELECT * FROM phpclassifieds_acc_users WHERE email = :email');
$sql->execute(array(':email' => $postData['email']));
if($sql->rowCount()>0)
{
return $this->response(0,'','The Email Address ('.$postData[email].') is already in use');
}
$sql = "UPDATE phpclassifieds_acc_users SET
type = :type,
username = :username,
password = :password,
name = :name,
address =:address,
address2 =:address2,
address_city = :address_city,
city =:city,
zipcode =:zipcode,
state =:state,
email =:email,
newsletter =:newsletter
WHERE user_id = :user_id";
try{
$stmt =$this->db->prepare($sql);
$stmt->bindParam(':type',$postData['type'],PDO::PARAM_STR);
$stmt->bindParam(':username',$postData['username'],PDO::PARAM_STR);
$stmt->bindParam(':password',$postData['password'],PDO::PARAM_STR);
$stmt->bindParam(':name',$postData['name'],PDO::PARAM_STR);
$stmt->bindParam(':address',$postData['address'],PDO::PARAM_STR);
$stmt->bindParam(':address2',$postData['address2'],PDO::PARAM_STR);
$stmt->bindParam(':address_city',$postData['address_city'],PDO::PARAM_STR);
$stmt->bindParam(':city',$postData['city'],PDO::PARAM_STR);
$stmt->bindParam(':zipcode',$postData['zipcode'],PDO::PARAM_STR);
$stmt->bindParam(':state',$postData['state'],PDO::PARAM_STR);
$stmt->bindParam(':email',$postData['email'],PDO::PARAM_STR);
$stmt->bindParam(':user_id',$postData['user_id'],PDO::PARAM_INT);
$var = $stmt->execute();
}
catch(PDOException $e) {
$err[] = var_dump($e->getMessage());
echo json_encode($err);
}
if($var){
$response = "Update Successfully done..";
$sqlSelect = $this->db->prepare('SELECT * FROM phpclassifieds_acc_users WHERE user_id = :user_id');
$sqlSelect->execute(array(':user_id'=>$postData['user_id']));
$data = $this->id2int($sqlSelect->fetch());
}else{
$response = "Update is unsuccessful ..";
}
return $this->response(1,$data,$response);
}
}
The problem is when i dont use try catch the output is "Update unsucessful...." and when i use try catch i get "Unexpected token s".
This line of code is strange
$err[] = var_dump($e->getMessage());
echo json_encode($err);
It's weird to encode a var_dump into json, you should just be able to do:
$err[] = $e->getMessage();
echo json_encode($err);
or you can get the error from errorInfo()
echo json_encode($this->db->errorInfo());
Don't forget to bind the newsletter parameter:
$stmt->bindParam(':newsletter',$postData['newsletter'],PDO::PARAM_STR);