Php webservice looping - php

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]

Related

Parse database table from GET request

Good morning
I've been struggling to work arround this recently, as I'm fairly new to PHP & MySQL in general.
I have a database with a table "videos" in which I store useful informations about videos and I have a document called search.php who will display specific videos based on GET Request.
A Request looks like this:
http://example.ex/search.php?tag=EXAMPLE1
The logic would be to store the tag value like this:
if(!empty($_GET["tag"])){
// Get videos from tag only
$curTag = strval($_GET["tag"]);
displayByTag($curTag); //the function that parse the database
}
I have my connection ready:
$server = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";
$conn = mysqli_connect($server, $username, $password, $db);
$query = "SELECT * FROM videos";
$response = array();
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)) {
$response[] = $row;
}
Technically as of right now, my table is stored inside $response[].
What I need to do is to parse the database and looks for the "tags" column, split its string value ("EXAMPLE1,EXAMPLE2,EXAMPLE3" in table) and then see if the GET value matches one of them.
That's when I need your help. I understand the logic, the steps, but can't "translate" it into PHP. Here's what I would do (human-language):
function displayByTag($tag) {
for each $video-item inside $array {
$tagsArray = explodes(",", $video-item[tags-column]); //That's how I split the tags stored inside the table
for i as integer = 0 to $tagsArray.length {
if $tagsArray(i) == $tag {
//THATS A MATCH
}
}
}
}
Is this the right way to do it ? And how can I translate that "human" language into PHP code ?
Thanks for the help.
After a little bit of testing and debugging I got my function working pretty easily. If anyone is interested:
function searchVideos($search) {
$currentSearchQueries = explode(" ", strtoupper($search)); //Split the searched tags in a array and make them to uppercase for easier comparaison.
//Establish a connection the MySql Database
$server = "localhost";
$username = "root";
$password = "";
$db = "mydatabase";
$conn = mysqli_connect($server, $username, $password, $db);
//Select all the entries from my 'videos' table
$query = "SELECT * FROM videos";
$response = array();
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
$response[] = $row; //Place them into a array
}
//Parse the array for matching entries
foreach ($response as &$video){ //Each entries goes through the process
foreach ($currentSearchQueries as $t) {
//We compare if one the tags searched matches for this particular entry
if((strtoupper($video[tags]) == $t) {
//THAT'S A MATCH
}
}
}
}
It was very fun to code, looking forward for new experiences !

PHP MySQL Query Where x = $variable from function

Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);

PDO select query return only the first row

I am new at PDO. I was trying to retrieve data from the database by using a search keyword,
but I only get the first row in which the keyword is match. It doesn't return other rows.
Here is my code::
<?php
$dsn = 'mysql:host=localhost;dbname=cois';
$user = 'root';
$password = '';
$pdo = new PDO($dsn, $user, $password);
$filmName = "shaban";
$sql= "SELECT * FROM staff_info WHERE fname = :filmName";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':filmName', $filmName, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();
while ($row = $stmt->fetchObject()) {
echo $row->surname.'</br>';
}
Currently it return only the first row.....it prints shekidere
How can i make it print both shekidere and kimweri
Any help?
Of course it stops always on the first row. You can use foreach instead of while and use an $arrayVariable[] = CurrentRow ; to fill it next by next.

I'm a little confused, PHP says $results is a non-object of the mysqli class

I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();

PHP5 Mysqli class is not outputting data

So i am trying to make a backup class and this is what I have so far. Issue is the $tbl_data is empty. What am I doing wrong.
The connection to the database is successful.
Without the 'echo $tbl_data', the '$current_table - current table' output is correct but if 'echo $tbl_data' is used, only the first table is shown ( trying to backup two tables to begin with ).
class mBackup{
private $_connection = ""; //db connection var
private $output = ""; //sql output
private $tbl_data = "";
private $tbl_row = "";
private $nfields = "";
private $create_table_query = "";
private $create_table_output = "";
public function __construct($dbhost,$dbname,$dbuser,$dbpassword){
$this->_connection = new mysqli($dbhost,$dbuser,$dbpassword,$dbname);
//possible connection error
if($this->_connection->connect_errno){
echo "Failed to connect to the DB";
}
else{
echo "Connected<br />";
}
}
public function backup_db(){
//get the table names from the DB and store in an array
$result = $this->_connection->query("SHOW TABLES");
//get the TABLE names
while($row = $result->fetch_row())
{
$table_names[] = $row[0];
}
//For each table
foreach($table_names as $current_table)
{
echo $current_table." - current table<br />"; //debug
$tbl_data = "";
$tbl_row = "";
$nfields = "";
$create_table_query = "";
$create_table_output = "";
//SELECT Everything from the table in use
$query = $this->_connection->prepare("SELECT * FROM ?");
$query->bind_param('s', $current_table);
$query->execute();
$query->bind_result($tbl_data);
$query->fetch();
echo $tbl_data."<br/>";
}
}
Try something like:
while ($query->fetch()) {
echo $tbl_data;
}
and see if that gets you anything. From the little that I know, bind_result binds columns in the result set to variables. If your table has 5 columns, you should have bind_result($var1, $var2, $var3, $var4, $var5) but since your number of columns are going to change depending on the table, I don't know if bind_result will give you what you need.
Try closing the prepared statement after every loop
$query->close();
or resetting.
$query->reset()
You can't use ? for the table name. See the second note in http://www.php.net/manual/en/mysqli.prepare.php for the allowed places for markers. So you'll have to construct the query by normal variable interpolateion:
$select = sprintf("SELECT * FROM `%s`", $current_table);
$result = $this->_connection->query($select);

Categories