I'm a junior android developer, and i was asked to make an app that connects to a mysql database and downloads some data.
I have no knowledge at all of PHP and mysql, so please forgive me in advance for any badly written code, if you'd like to comment and thus help me improve my code writing, i'll be grateful :)
I had no issues with downloading all data from a database and passing it to the app through my simple API, but when i'm trying to pass only some entries of another database (that's to say, with a get function with a parameter in it) i'm having some issues.
I'm posting the code right here.
DbOperation.php
class DbOperation
{
private $con;
//Class constructor
function __construct()
{
require_once dirname(__FILE__) . '/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
//This is the WORKING function, i have no issues with it.
function getEvento(){
$stmt = $this->con->prepare("SELECT event_id, event_title, event_begin, event_end, event_category, event_link, event_label FROM wp_my_calendar");
$stmt->execute();
$stmt->bind_result($id, $titolo, $inizio, $fine, $categoria, $link, $luogo);
$eventi = array();
while($stmt->fetch()){
$evento = array();
$evento['id'] = $id;
$evento['titolo'] = $titolo;
$evento['inizio'] = $inizio;
$evento['fine'] = $fine;
$evento['categoria'] = $categoria;
$evento['link'] = $link;
$evento['luogo'] = $luogo;
array_push($eventi, $evento);
}
return $eventi;
}
From now on, what i'm doing is: first (getUtenteId) i get the submission_id from the mail of the user. Then (getUtenteDati) from the submission_id i can get all the user's values and return them. I'll call both get functions in the Api.php file.
(Here we're still in DbOperation.php)
function getUtenteId($email){
$idutente = $this->con->prepare("SELECT submission_id FROM wp_rm_submissions WHERE user_email='$email'");
$idutente->execute();
$idutente->bind_result($sub_id);
$idutente->fetch();
//echo $sub_id;
return $sub_id;
}
function getUtenteDati($utenteid) {
$stmt = $this->con->prepare("SELECT field_id, value FROM wp_rm_submission_fields WHERE submission_id='$utenteid' ORDER BY field_id");
$stmt->execute();
$stmt->bind_result($fieldid, $valori);
$dati = array();
while($stmt->fetch()){
$dato = array();
$dato['id'] = $fieldid;
$dato['valore'] = $valori;
//echo $valori;
array_push($dati, $dato);
}
return $dati;
}
}
?>
And here's the Api.php file
<?php
require_once '../includes/DbOperation.php';
function isTheseParametersAvailable($params){
$available = true;
$missingparams = "";
foreach($params as $param){
if(!isset($_POST[$param]) || strlen($_POST[$param])<=0){
$available = false;
$missingparams = $missingparams . ", " . $param;
}
}
if(!$available){
$response = array();
$response['error'] = true;
$response['message'] = 'Parameters ' . substr($missingparams, 1, strlen($missingparams)) . ' missing';
echo json_encode($response);
die();
}
}
$response = array();
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'geteventi':
$db = new DbOperation();
$response['error'] = false;
$response['message'] = 'Calendario aggiornato';
$response['messagedata'] = 'Data aggiornata';
$response['eventi'] = $db->getEvento();
break;
case 'getutente':
$db = new DbOperation();
//isTheseParametersAvailable(array('emailutente')); Commented because it returns error, don't know why.
$response['error'] = false;
$response['message'] = 'Dati utente scaricati';
$response['messagedata'] = 'Dati utente scaricati';
$emailutente = $_GET['emailutente'];
$idutente = $db->getUtenteId($emailutente);
//echo "id utente $idutente";
$dbdue = new DbOperation();
$response['utente'] = $dbdue->getUtenteDati($idutente);
break;
}
}else{
$response['error'] = true;
$response['message'] = 'Errore nel tentativo di aggiornare i dati, controlla la connessione a internet e riprova';
}
echo json_encode($response);
If i call this API correctly (http://.../Api/v1/Api.php?apicall=getutente&emailutente=user#mail.it), what i get is a blank page.
If i write "emailutente" wrong in the url (like emailsuteente), i get no error, but the response is empty.
{"error":false,"message":"Dati utente scaricati","messagedata":"Dati utente scaricati","utente":[]}
I tried to use an echo inside my getUtenteDati function, and it prints all the data i need correctly.
Any clues?
Thank you in advance!
EDIT: I tried to use this code in my local DB, and it's working. Issue still remains inside my remote DB. And it's weird, because with a simple ECHO inside the get function, i'm getting all the values i want. But it simply seems to refuse to give them to me inside an array.
Just a small update. The code was actually correct. The issue was with the Wordpress database refusing to return sensible data with my query from remote. I managed to get them in a safer way, with a simple self-made plugin:
global $wpdb;
[...]
if( is_user_logged_in() AND ! is_admin() ) {
$current_user = wp_get_current_user();
$email = $current_user->user_email;
$userid= $wpdb->get_var($wpdb->prepare("SELECT [...], $email);
Related
I have created a MYSQL Procedure to fetch employee details. The calling procedure is
function call_procedure($procedure)
{
require_once("database_connect.php");
$db = Database::getInstance();
$mysqli = $db->getConnection();
$result = $mysqli->query("CALL $procedure");
return $result;
}
I call this function from another page by using this function:
function get_emp_details($parameters){
//create the query
$procedure = "fetchEmpDetails($parameters)";
$result = call_procedure($procedure);
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// products node
$response['DATA'] = sqltoarray($result);
// success
$response['RESULT'] = 0;
$response['MESSAGE'] = 'Employee Details found';
$response['REQUEST'] =1;
}
else {
$response['DATA'] = '';
// no products found
$response['RESULT'] = 1;
$response['MESSAGE'] = "Incorrect Employee ID";
$response['REQUEST'] =1;
}
// echo no users JSON
return $response;
}
When I am using both the functions in the same file it is working fine. However, when I am using the two functions in different files, I am not getting any results when calling get_emp_details function.
To debug, I tried to echo values of $procedure and $result. The string in $procedure is as expected, but the value I am receiving in $result is nothing.
The login() function which is also defined in the same file as the get_emp_details() function is working fine. It is the get_emp_details() that is causing the problem.
Can anyone help me with this?? Thanks in Advance...
I am about to lose my mind.I dont have any php experince and I am struggling about php web service.
Here is my code;
<?php
private $username2 = "";
private $password2 = "";
private $DB_CONNECTION;
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "dptest";
function __construct()
{
$this->DB_CONNECTION = mysqli_connect($this->servername, $this->username,
$this->password, $this->dbname);
}
function getUserType(){
$sql = "SELECT usertype FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION,$sql);
//$value = mysqli_fetch_array($result);
while(!is_null($value = mysqli_fetch_array($result))){
return $value['usertype'];
}
}
}
This is my function code.The other is my login code;
<?php
include_once 'Authentication.php';
use user\Authentication;
$auth = new Authentication();
$auth->prepare($_POST);
$userStatus = $auth->isUserValidToLogIn();
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'access granted';
$json['usertype'] = $auth->getUserType();
echo json_encode($json);
} else {
$json['success'] = 0;
$json['message'] = 'error!';
echo json_encode($json);
}
I am trying to get the user's type but when try to get the data form phpmyadmin local database it only gives the first column's usertype.When I try to get 2nd,3rd,4th so on.. user's usertype it doesnt return anything and blank page shows up on postman app.
Also my database looks like this;
usertype username password
admin despro 1234
client test 1234
client despro2 1234
client despro3 1234
The reason you are only getting one column back is because you only request the one column. In order to get the columns you want you need to explicitly request them in your query or use '*' in order to get all columns back. So your query should look like this in order to get all columns from the data table:
$sql = "SELECT * FROM `login_test` WHERE username = '". $this->username2."'AND password = '".$this->password2."'";
In general, I highly recommend that you stop using MySQLi extension and start using PHP Data Objects (PDO). It makes it easy to use prepared statements. Which also makes your code safer.
Then your query could look something like this (this is NOT the complete code):
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT *
FROM login_test
WHERE userName = :username
AND pass = :password;';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username2, PDO::PARAM_STR);
$stmt->bindParam(':password', $password2, PDO::PARAM_STR);
$res = $stmt->execute();
if ($res) {
$response["userdata"] = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
}
Note that the code above is for returning multiple rows of data. If you just want the one row then use something like this:
if ($res) {
$response["userdata"] = array();
$myData = array();
$myData["usertype"] = $row["usertype"];
$myData["username"] = $row["username"];
array_push($response["userdata"], $myData);
}
removing the 'while' statement.
You might want to take a look at this answer I gave, recently. It is a comprehensive example of using a webservice from an Android app.
How to insert all the SQL table data into an array in java [android studio]
I am making an app that will list employees by a certain store in a listview. My current function in my DB_Functions.php file is:
public function getEmployeeList($name) {
$stmt = $this->con->prepare("SELECT employee_name FROM employees WHERE name = ?");
$stmt->bind_param('s', $name);
if ($stmt->execute()) {
$employee_list = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (empty($employee_list)) {
return NULL;
} else {
return $employee_list;
}
}
}
and in my employees.php file I have the following code:
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array('error' => FALSE);
if (isset($_POST['name'])) {
$name = $_POST['name'];
$employee_list = $db->getEmployeeList($name);
if ($employee_list != false) {
$response['error'] = FALSE;
//EMPLOYEE LIST OBJECT HERE
} else {
$response['error'] = TRUE;
$response['error_msg'] = 'No employees have been added to this profile.';
echo json_encode($response);
}
} else {
$response['error'] = TRUE;
$response['error_msg'] = 'You have not logged in to your store\'s account, please log in first.';
echo json_encode($response);
}
?>
I would like to have an employee_list object in the commented space above. Something like:
$response['employee_list']['0'] = $employee_list['0'];
$response['employee_list']['1'] = $employee_list['1'];
$response['employee_list']['2'] = $employee_list['2'];
etc... etc...
After that JSONObject is returned to the android app, the contents will be listed in a listview. I would need a for loop (I think) because the employee number will never be known since each store will be able to add and remove employees as they wish. Can someone point me in the right direction and also advise if I am using the correct approach as far as the rest of the code. Thanks.
First, in your DB_Functions.php, you should be returning the mysqli_result object.
Hence your DB_Functions should be this:
public function getEmployeeList($name) {
$stmt = $this->con->prepare("SELECT employee_name FROM employees WHERE name = ?");
$stmt->bind_param('s', $name);
if ($stmt->execute()) {
// we get the mysqli_result object without calling the fetch_assoc() on it
$result = $stmt->get_result();
$stmt->close();
// if the count is less than 1, no result found, hence return null
if ($result->num_rows < 1) {
return null;
} else {
// we return the mysqli_result object without calling the fetch_assoc() on it
return $result;
}
}
}
In your employees.php, what you want is something like this:
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array('error' => FALSE);
if (isset($_POST['name'])) {
$name = $_POST['name'];
$result = $db->getEmployeeList($name);
// do an early check for if result returns null or is not set
if (is_null($result) || !$result) {
$response['error'] = TRUE;
$response['error_msg'] = 'No employees have been added to this profile.';
} else {
$response['error'] = FALSE;
//EMPLOYEE LIST OBJECT HERE
// since $result->fetch_assoc() returns one row at a time, you want to loop through each row and get the appropriate data
while ($row = $result->fetch_assoc()) {
// inject the current into the employee_list array
$response['employee_list'][] = $row;
}
}
} else {
$response['error'] = TRUE;
$response['error_msg'] = 'You have not logged in to your store\'s account, please log in first.';
}
// echo response gets called no matter what
echo json_encode($response);
Hope it helps
I have a function to search for records by course name:
<?php
function searchByCourse()
{
if (isset($_POST["course_title"])) {
//Copy to local var
$course_title = $_POST["course_title"];
$stmt = self::$conn->prepare("SELECT student_id, student_name, course_title FROM student_info WHERE course_title = ?");
$stmt->bind_param("s", $course_title);
$result = $stmt->execute();
if ($result === FALSE) {
$stmt->close();
return FALSE;
} else {
$results_array = array();
$stmt->bind_result($student_id, $student_name, $course_title_found);
while ($stmt->fetch()) {
echo "Fetch! \n";
$row = array();
$row["student_id"] = $student_id;
$row["student_name"] = $student_name;
$row["course_title"] = $course_title;
$results_array[] = $row;
}
$stmt->close();
return $results_array;
}
} else {
return FALSE;
}
}
?>
The code seems to execute fine but when I test it using curl for course_title=Computing it should return 3 results. However the echo "Fetch!" is never displayed. It seems to be that there is nothing for it to fetch. It's driving me a little crazy. I've checked all the var names in the database and they match up fine. Any ideas what I could be doing wrong here?
EDIT:
This method is part of my class DbHandler. $conn is a protected static MySqli connection object created in function__contruct().
called like this:
$db = new DbHandler();
$db->searchByCourse();
I have other database functions that work fine for this design pattern. The function is being called correctly. I have also checked the $_POST["course_title"] and that is being passed correctly.
I have been connecting my android app to my wamp server but one day it just woke up giving this error BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.43.71/database/login.php. I am sure its not my java code but there is something wrong with my server, i am not very familiar with configuring the server and i am drowning in my frustration. What i dont understand is one time it was working and it just decided not to.
This is what i tried
1. Running the script using the browser and it works fine
2. Uninstalling and reinstalling wamp server and it did not work
3. Moving my database from localhost to an online server and it did not work
3. I realised that only php scripts in which i have to post parameters give this error, in cases where i just have to retrieve data from the server without parameters it works
Below is my login script and my database connection. I am sure the database connection is working fine
<?php
$response = array();
$array = array();
$details = array();
// check for required fields
if (!empty($_POST)) {
$phone_number = $_POST['user_phone_number'];
$password = md5($_POST['user_password']);
include 'database.php';
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql2 = "SELECT * FROM users WHERE user_phone_number OR user_email = ? AND user_password = ?";
$result2 = $pdo->prepare($sql2);
$result2->execute(array($phone_number,$password));
while ($row = $result2->fetch(PDO::FETCH_ASSOC)){
$array["user_phone"] = $row["user_phone"];
$array["user_id"] = $row["user_id"];
$array["user_imei"] = $row["user_imei"];
$array["user_name"] = $row["user_name"];
$array["user_surname"] = $row["user_surname"];
$array["user_phone_number"] = $row["user_phone_number"];
$array["user_email"] = $row["user_email"];
$array["user_password"] = $row["user_password"];
}
if($result2){
if($array == null){
$array["user_phone"] = "error";
$array["message"] = "Wrong phone number or password";
$json = json_encode($array);
echo $json;
}else{
$json = json_encode($array);
echo $json;
}
}
} else {
$array["user_phone"] = "0";
$array["message"] = "Required field(s) is missing";
echo json_encode($array);
}
Database::disconnect();
?>
Database Connection
<?php
class Database{
private static $dbName = 'testdb';
private static $dbHost = 'localhost';
private static $dbUsername = 'root';
private static $dbPassword = '';
private static $cont = null;
public function __construct() {
die('Init not allowed');
}
public static function connect(){
//Open connection through the who;e application
if(null == self::$cont){
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbPassword);
} catch (PDOException $ex) {
die($ex->getMessage());
}
}
return self::$cont;
}
public static function disconnect(){
self::$cont == null;
}
}
?>
The problem is that may be your ip address is dynamically and it is change. Sometimes it work because your current ip address is equals to your set (192.168.43.71). When you start the app should be sure that your ip address which you set is the same like your current. It is possible with ifconfig terminal command.