Get values from database table with ID from Unity - php

I have a database table with values, the primary key being ID. Now I am trying to receive the values of the table with the referenced ID from Unity. How do I send the referenced ID from Unity to this php file so that only the values from this ID should be received.
Currently I am receiving all the values of the table from all IDs.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class CheckForExistingID : MonoBehaviour {
public string[] Items;
public string ID = "001"; //Referenced ID
public string Name;
public string Age;
void Start () {
StartCoroutine (ReceiveValues());
}
IEnumerator ReceiveValues () {
WWW data = new WWW ("http://localhost/GetValue.php?id="+ID);
yield return data;
if (data.error != null) {
print (data.error);
} else {
print ("Received");
dataString = data.text;
Items = dataString.Split (';');
Name = Items[0];
Age = Items[1];
}
}
}
GetValue.php
<?php
...
...
...
$id = $_GET['id'];
$sql = "SELECT Name, Age FROM Students WHERE ID = $id";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)){
echo "".$row['Name'] . ";";
echo "".$row['Age'] . ";";
}
}
?>

NOTE Do NOT use WWW as derHugo had pointed out, it is now obsolete. Similarly sanitize all data using prepared statements. Skip to the edit marker to find an updated answer.
I am not sure you are posting the data properly. You should use a WWWForm, add the fields you want and then handle them on the PHP side. I would also heavily consider adding some form of error handling in PHP with an echo to know if something failed.
On mobile so excuse the formatting for now I'll fix it later if it needs it.
string url = "http://localhost/GetValue.php";
WWWForm form = new WWWForm();
form.AddField("id", "TheIDHere");
WWW www = new WWW(url, form);
yield return www;
...
On the PHP side of things, it can look like
<?php
if (isset($_REQUEST["id"])) {
echo "Received ". $_REQUEST["id"]. " success!";
exit();
} else {
http_status_code(400);
echo "Request Failed";
}
Edit: As pointed out by derHugo, WWW is now obsolete, and is replaced by WebRequests. The above c# code should look like
WWWForm form = new WWWForm();
form.AddField("id", "yourID");
UnityWebRequest www = UnityWebRequest.Post("http://localhost/GetValue.php", form);
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Sucess");
}
As well, derHugo had pointed out that you are not sanitizing your data at all, so you would be subject to SQL Injections. Here is roughly what you would want to do to use prepared statements
// prepare a statement using the ID
$stmt = $mysqli->prepare("SELECT Name, Age FROM Students WHERE ID = ?");
// bind the ID from our POST
$stmt->bind_param("i", $_POST['id']);
// execute our prepare statement
$stmt->execute();
// store the result
$stmt->store_result();
// we have no found id
if($stmt->num_rows === 0) exit('No Data');
// bind the results we are looking for from our prepared statement
$stmt->bind_result($idName, $idAge);
// fetch the results from the table
$stmt->fetch();
// echo your results to Unity
echo $idName;
echo $idAge;
// deallocate the statement
$stmt->close();

Related

Trying to retreive int type from function and compare it with $_Get value (mysql PHP)

I trying to retreive int type from database and compare it with $_Get value
Here is the code for when the user click on the button
if(isset($_GET['btn_placeorder']))
{
$Quantity_Ordered=(int)$_GET['Quantity_Ordered'];
**# retreivng another value from function to compare it as integer**
$number= (int)$auth_user->Blood_Bankavaliable ($Blood_BankID,$Type_Ordered);
try
{
if ($Type_Ordered=="" || $Quantity_Ordered=="")
{
$error[] = "Valid data is required!";
}
else if($Quantity_Ordered >$number) {
$error[] = "This Number is not avaliable in our Stock !";
}
Here is the code for the function
function Blood_Bankavaliable($blood_bankID,$Type_Ordered) {
global $conn;
# query for getting the value from the database
$query = "select sum(Blood_quantity) as d from Donor_Blood_Bank where Blood_Type=$Type_Ordered and blood_bankID= $blood_bankID";
try {
$statement = $this->conn->prepare($query);
$statement->execute();
$result = $statement->fetchall;
return $result;
} catch(PDOException $e)
{
echo $e->getMessage();
}
}
I don't know what is the problem with my code any help?
First, it should be $result = $statement->fetchAll();(a function or method), not $result = $statement->fetchall (a property).
Second, please read the manul, fetchall() return an array. therefore you can't cast it to int directly. run print_r( $auth_user->Blood_Bankavaliable($Blood_BankID,$Type_Ordered) ); to see yourself.

Insert query gives "Couldn't fetch mysqli_stmt" warning but sends still data to database

I have a form with 2 drop down lists. Both with values from database tables.
When a visitor submits then the next things will occure:
A select query will compare the choices (id's)/POST values with the values (id's) in the database tables. The query will be fetched in the while loop. In the while loop is a if-else which controls if the values are equal to each other. When they are then run else.
In else there is the insert query which saves the values (id's) in a new database table.
I use prepared statements for both the select and the insert queries.
After fetching the select query I close it in else ($selControl->close();) and start the 2nd query (insert).
When I run the website with a submit then I get the error "Couldn't fetch mysqli_stmt" for the select query. But still it works and inserts into the DB table.
When I write $selControl->close(); (inclusive/exclusive $insKeuze->close(); from insert) after } of the 3rd else or after } after while then I get the error that the 1st query must be closed before a new prepare statement (that's logic).
Without a close statement gives also a "close-before-prepare" error.
I updated my code.
I added bind_param. It sends the data to the database, but gives the error.
What do I need to do to stop the error?
If someone can help me, thanks in advance!
The code: insert.php
<?php
// Include database configuration file
include ("dbConfig.php");
$kLand = $_POST["landen"];
$kGerecht = $_POST["gerechten"];
// If submit and landKeuze is not empty and gerechtKeuze is not empty
// --> control and validate the values and send to database.
if (isset($_POST["submit"]) && !empty($kLand) && !empty($kGerecht))
{
// If query is prepared then execute the query.
// Query to select data from table landen with inner join table gerechten.
if ($selControl = $mysqli->prepare("SELECT landen.land_id, gerechten.gerecht_id FROM landen INNER JOIN gerechten ON landen.land_id = gerechten.land_id WHERE landen.land_id = ? AND gerechten.gerecht_id = ?"))
{
$selControl->bind_param("ii", $kLand, $kGerecht);
if (!$selControl->execute())
{
echo "Failed to execute the query controle: " . $mysqli->error;
}
else
{
$selControl->bind_result($lLand_id, $gGerecht_id);
while ($selControl->fetch()) // <-- Coudn't fetch
{
// If selected land (land_id) is not the same as land_id in table landen
// or selected gerecht (gerecht_id) is not the same as gerecht_id in table gerechten --> send echo.
if ($kLand != $lLand_id || $kGerecht != $gGerecht_id)
{
// Message when the combination is not correct
echo "<script>alert('Deze combinatie bestaat niet. Doe een nieuwe poging!');</script>";
}
// Else insert the selected values in table landGerecht.
else
{
$selControl->close();
// If query is prepared --> bind the columns and execute the query.
// Insert statement with placeholders for the values to database table landGerecht
if ($insKeuze = $mysqli->prepare("INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)"))
{
// Bind land_id and gerecht_id as integers with $landKeuze and $gerechtKeuze.
$insKeuze->bind_param('ii', $kLand, $kGerecht);
// If statement is not executed then give an error message.
if (!$insKeuze->execute())
{
echo "Failed to execute the query keuze: " . $mysqli->error;
}
$insKeuze->close();
}
// Else give an error message.
else
{
echo "Something went wrong in the query keuze: " . $mysqli->error;
}
}
}
}
}
else
{
print_r($mysqli->error);
}
// After sent to database go back to keuze.php.
echo "<script>location.replace('keuze.php');</script>";
}
?>
This structure gives the same error:
<?php
while ($selControl->fetch())
{
echo "<script>alert('". $kLand . $kGerecht . $lLand_id . $gGerecht_id . "')</script>";
// If selected land (land_id) is not the same as land_id in table landen
// or selected gerecht (gerecht_id) is not the same as gerecht_id in table gerechten --> send echo.
if ($kLand == $lLand_id && $kGerecht == $gGerecht_id)
{
$selControl->close();
// If query is prepared --> bind the columns and execute the query.
// Insert statement with placeholders for the values to database table landGerecht
if ($insKeuze = $mysqli->prepare("INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)"))
{
// Bind land_id and gerecht_id as integers with $landKeuze and $gerechtKeuze.
$insKeuze->bind_param('ii', $kLand, $kGerecht);
// If statement is not executed then give an error message.
if (!$insKeuze->execute())
{
echo "Failed to execute the query keuze: " . $mysqli->error;
}
$insKeuze->close();
} else // Else give an error message.
{
echo "Something went wrong in the insert query connection: " . $mysqli->error;
}
} else // Else insert the selected values in table landGerecht.
{
// Message when the combination is not correct
echo "<script>alert('Deze combinatie bestaat niet. Doe een nieuwe poging!');</script>";
}
}
?>
So as you said in the comments, you believe you're getting a conflict between your mysql connections. I've gone ahead and created a class that should resolve this.
landen.php
class landen{
//define our connection variable, this is set in __construct
private $mysqli;
//this function is called when you create the class. $l = new landen($mysqlconn)
public function __construct($mysqli){
$this->mysqli = $mysqli;
}
//setter for kLand
private $kLand = 0;
public function setKland($k){
$this->kLand = $k;
}
//setter for kGerecht
private $kGerecht = 0;
public function setKGerecht($k){
$this->kGerecht = $k;
}
//run is our main function here.
//if there was a return from select, it runs the insert.
//will return true if select + insert BOTH pass.
public function run(){
if($this->select()){
return $this->insert();
}
return false;
}
private function select(){
$q = "SELECT landen.land_id, gerechten.gerecht_id FROM landen INNER JOIN gerechten ON landen.land_id = gerechten.land_id WHERE landen.land_id = ? AND gerechten.gerecht_id = ?";
if($stmt = $this->mysqli->prepare($q)){
$stmt->bind_param("ii",$this->kLand,$this->kGerecht);
if($stmt->execute()){
while ($stmt->fetch()){
/*
In your original code, you had a check to see if
your post variable was the same as your returned query variables.
This was not required as you are selecting from your database with those.
They will **always** equal the post variables.
Line I'm disputing: if ($kLand != $lLand_id || $kGerecht != $gGerecht_id)
*/
return true;
}
}else{
print_r("Error in select execute: {$this->mysqli->error}");
}
}else{
print_r("Error in select prepare: {$this->mysqli->error}");
}
return false;
}
private function insert(){
$q = "INSERT INTO lab_stage_danush . landGerecht (land_id, gerecht_id) VALUES ( ?, ?)";
if($stmt = $this->mysqli->prepare($q)){
$stmt->bind_param("ii",$this->kLand,$this->kGerecht);
if($stmt->execute){
return true;
}else{
print_r("Error in insert execute {$this->myqsli->error}");
}
}else{
print_r("Error in insert prepare {$this->mysqli->error}");
}
return false;
}
}
And here's an example on how you run this;
insert.php
<?php
require_once("dbConfig.php");
if(isset($_POST["submit"]) && !empty($_POST['landen']) && !empty($_POST['gerechten'])){
//Call the class code when we need it
require_once("landen.php");
//create the class when we need it.
$landen = new landen($mysqli);
//set our variables
$landen->setKland($_POST['landen']);
$landen->setKGerecht($_POST['gerechten']);
//landen run returns True if the select + insert statment passed.
//It will return false if they fail.
//if they fail, the page will not change and the errors will be outputted.
//Or it's failing because nothing has been returned by the select function.
if($landen->run()){
//send out header to go to Keuze page,
//you had a javascript location function here.
header("Location: keuze.php");
die();
}else{
//by default, let's say our queries are running fine and the only reason the select failed is because
//the database couldn't find anything.
echo "Nothing found with {$_POST['landen']} and {$_POST['gerechten']}. Please try again!";
}
}

Unable to update values to database in PHP and MySQL

I am trying to update the value to database, but one way or an another i am not able to.
Code:
<?php
include 'init.php';
$dataid = $_POST['data_id'];
if(isset($dataid))
{
/*user connects to database and performs some operation here*/
/* values from database is returned and user passes the same to below function */
calculateamount($kk_data_id,$kk_egg,$kk_cash,$kk_in,$kk_out,$kk_expenditure,$kk_cashout,$kk_wholesale1,$kk_wholesale2,$kk_wholesale3,$kk_touch,$kk_galtha,$kk_kotla,$wholesale_1,$wholesale_2,$wholesale_3,$touch,$galtha,$kotla,$retail,$prevegg,$prevcash);
}
function calculateamount($kk_data_id,$kk_egg,$kk_cash,$kk_in,$kk_out,$kk_expenditure,$kk_cashout,$kk_wholesale1,$kk_wholesale2,$kk_wholesale3,$kk_touch,$kk_galtha,$kk_kotla,$rwholesale_1,$rwholesale_2,$rwholesale_3,$rtouch,$rgaltha,$rkotla,$rretail,,$prevegg,$prevcash)
{
/*performs Mathematical operations
with data retrieved and passes the final values to the below function to update to database*/
//ALL THE VALUES ARE CONVERTED TO STRING BEFORE PASSING ON TO THE BELOW FUNCTION
updatevaluestodatabase($finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,$finaltotamount,
$finaltottally);
}
function updatevaluestodatabase($finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,$finaltotamount,
$finaltottally)
{
$updatedata = "UPDATE kk_data SET wholesale1_amt=?,wholesale2_amt=?,wholesale3_amt=?,touch_amt=?,galtha_amt=?,kotla_amt=?,
kk_retail=?,retail_amt=?,kk_total_amount=?,kk_final_tally=? where kk_data_id = ?";
$updatestmt = mysqli_prepare($con, $updatedata);
mysqli_stmt_bind_param($updatestmt, sssssssssss,$finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,
$finaltotamount,$finaltottally,$dataid);
mysqli_stmt_execute($updatestmt);
mysqli_stmt_store_result($updatestmt);
$response = array();
$response["success"] = false;
if(mysqli_stmt_affected_rows($updatestmt) > 0 )
{
$response["success"] = true;
}
header('Content-Type: application/json');
echo json_encode($response);
}
?>
OUTPUT
Every time I run the below script in postman ('data_id' = value) or through application:
$response["success"] = false;
is returned always . Data is not updated to the database.
What I tried
Instead of using mysqli_stmt_affected_rows($updatestmt) I tried executing using mysqli_stmt_execute($updatestmt); in the if statement. But no luck there
I am unable to figure out where the issue is or if am incorrect in calling the function.
NOTE: I thought I would post a minimized code to avoid clumsiness.

Search user using part of the name

I have this PHP code:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s'",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
But this only returns the user that matches the name exactly.
I'd like to return all users containing that name string, for example:
dani -> daniel, dani_56, dani563, elnenedani, ...
It is usually done by putting in PHP: %dani% but as I have put the %s to grab the variable $user, I do not know how to put it.
Any idea?
It is not a great Question. If you have searched well in Stackoverflow you would have go it the answer.. As you asked the Question the answer is.. Instead of Equal use LIKE:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username LIKE %'%s'%",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
It seems the PHP code and DB is working well. Checkout the below links for the error:
iOS 5 JSON Parsing Results in Cocoa Error 3840
Cocoa error 3840 using JSON (iOS)
The Operation couldn't be completed. (Cocoa error: 3840.)
Cocoa Error 3840 - NSJSONSerialization
You should use the LIKE syntax. Make sure to include % to indicate wildcards:
query('SELECT IdUser, username FROM login
WHERE username LIKE "%' . $user . '%"')
My query() function is
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
I do not get fixed. This code is for an ios app that uses AFNetworking, might please that helps you know what happens because I do not get it

PDO version of mysql_num_rows($result)==0) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Alternative for mysql_num_rows using PDO
^ I believe it isn't the same question - The other authors code is different to mine, which needed a different answer. I successfully got my answer from this post and marked it as answered. Everything is working fine now (no help from the other 'duplicate' thread.
I want to display a "No Client Found" message if no results are found, Is there a PDO method to the following code?:
$result = mysql_query($sql) or die(mysql_error()."<br />".$sql);
if(mysql_num_rows($result)==0) {
echo "No Client Found";
I tried the following...
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXXXXXXXXXX;charset=utf8','XXXXXXXXXXXX', 'XXXXXXXXXXXX');
$query = $db->query('SELECT * FROM client');
if ($query == FALSE) {
echo "No Clients Found";
}
else
{
foreach($query as $row)
{
<some code here>
}
}
?>
Am I missing something?
I've read: http://php.net/manual/en/pdostatement.rowcount.php but hasn't helped
<?php
$db = new PDO('mysql:host=localhost;dbname=XXXXXXXXXXXX;charset=utf8','XXXXXXXXXXXX', 'XXXXXXXXXXXX');
$query = $db->query('SELECT * FROM client WHERE ID = 10');
if ($query->rowCount() != 1) {
echo "No Clients Found";
}
else
{
foreach($query as $row)
{
<some code here>
}
}
?>
In PDO, rowCount method is used to count the returned results. Your query must select some thing unique, like an email address or username if you want to check for unique existence, else, if you want at least find one row, change the condition to this:
if ($db->rowCount() == 0)
There is a tutorial: PDO for MySQL developers.
PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement in some databases. Documentation The code below uses SELECT COUNT(*) and fetchColumn(). Also prepared statements and try & catch blocks to catch exceptions.
<?php
// Get parameters from URL
$id = $_GET["client"];
try {
$db = new PDO('mysql:host=localhost;dbname=XXXX;charset=utf8', 'XXXX', 'XXXX');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare COUNT statement
$stmt1 = $db->prepare("SELECT COUNT(*) FROM client WHERE client = ?");
// Assign parameters
$stmt1->bindParam(1,$id);
$stmt1->execute();
// Check the number of rows that match the SELECT statement
if($stmt1->fetchColumn() == 0) {
echo "No Clients Found";
}else{
//echo "Clients Found";
// Prepare Real statement
$stmt2 = $db->prepare("SELECT * FROM client WHERE client = ?");
// Assign parameters
$stmt2->bindParam(1,$id);
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
$stmt2->execute();
while($row = $stmt2->fetch()) {
//YOUR CODE HERE FROM
// Title
echo '<div id="portfolio_detail">';
//etc.etc TO
echo '<div><img src="'."/client/".$row[client].'_3.png"/></div>';
echo '</div>';
}//End while
}//End if else
}//End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you have an Error. ". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myfile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
//Close the connection
$db = null;
?>

Categories