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.
Related
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();
i start write a script with php , for installation stage i face to a problem.
when i install sql table with php code and after that "in same code page" i want insert admin_user information to user table , without any error user information not inserted in database but when i install Manually database table and after that run same code for insert admin_user information inserted run good and information inserted in database.
My Query Run PDO Method :
// Execute query
public function Tbmedia_runquery($query_body = "" , $parameter_array ="" ){
$query = $query_body;
$stmt = $this->Tbmedia_connection->prepare($query);
if(is_array($parameter_array)){
// declare bind_param variable
foreach ($parameter_array as $key => &$value) {
$stmt->bindParam(":$key",$value);
//':$key'
}
}
$stmt->execute();
$stmt->closeCursor();
return $stmt;
}
And this is My Create Database Table Function :
//Create DB Table
function Tbmedia_dbcreator($db_con){
$dir_sql = __DIR__."/../../install/tbmedia.sql";
if(!file_exists($dir_sql) or is_writable($dir_sql)){
$line_array = file($dir_sql);
$query_line = "";
$query = "";
foreach ($line_array as $value) {
if(substr($value,0,2) == "--")
continue;
$query_line .=$value;
if (substr(trim($value),-1,1) == ";"){
try{
$query = $db_con->Tbmedia_runquery($query_line);
$query_line = "";
}catch (Exception $e){
$file_name = basename($e->getFile());
$file_line = $e->getLine();
Tbmedia_die();
}
}
}
}else{
Tbmedia_die();
}
}
And this is simple insert sql for insert user user information after run function Tbmedia_dbcreator() :
$db_con->Tbmedia_runquery('INSERT INTO `tbmedia`.`tbmedia_user` (`user_name`,`user_state`) VALUE ("FARAMARz",1)');
Why this is happening ? can't create table and insert data to it in one page code ?
I have written a php script to retrieve data from mysql for a particular username. The username is passed in select query and i am checking the php script using postman. Following is my php code
<?php
//getting the database connection
require_once 'MyDbConnect.php';
//an array to display response
$response = array();
//if it is an api call
//that means a get parameter named api call is set in the URL
//and with this parameter we are concluding that it is an api call
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'getSpecificData':
case 'getSpecificData':
if(isTheseParametersAvailable(array('your_username'))){
//getting values
$your_username = $_POST['your_username'];
$heroes = array();
$sql = "SELECT your_username,your_mobile,referral_name,referral_contact,referral_email,
loan_type,loan_amount FROM mytable WHERE your_username = ? ";
$sql->bind_param("s",$your_username);
$stmt->execute();
$stmt->bind_result($your_username, $your_mobile,$referral_name,$referral_contact,
$referral_email,$loan_type,$loan_amount);
//looping through all the records
while($stmt->fetch()){
$temp = [
'your_username'=>$your_username,
'your_mobile'=>$your_mobile,
'referral_name'=>$referral_name,
'referral_contact'=>$referral_contact,
'referral_email'=>$referral_email,
'loan_type'=>$loan_type,
'loan_amount'=>$loan_amount
];
//pushing the array inside the hero array
array_push($heroes, $temp);
}
echo json_encode($heroes);
}
break;
default:
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
}
else{
//if it is not api call
//pushing appropriate values to response array
$response['error'] = true;
$response['message'] = 'Invalid API Call';
}
function isTheseParametersAvailable($params){
//traversing through all the parameters
foreach($params as $param){
//if the paramter is not available
if(!isset($_POST[$param])){
//return false
return false;
}
}
//return true if every param is available
return true;
}
?>
The problem is in the select query. When i write the select query as i mentioned above in my php code i get nothing. but if i write the select query as follows i get proper data
$sql = "SELECT your_username,your_mobile,referral_name,referral_contact,referral_email,
loan_type,loan_amount FROM mytable WHERE your_username = 'Rohan' ";
Can somebody please explain me the cause of error? Any help would be greatly appreciated.
You're missing the binding of the variable:
// $stmt->bind_param("ss",$your_username);
Is already in your code. Change it to:
$stmt->bind_param("s",$your_username);
The "s" indicates the variable is a string, the binding "replaces" the "?" in the query.
EDIT:
Than use this snippet instead ;)
$your_username = $_POST['your_username'];
//creating the query
$stmt = $conn->prepare("SELECT id,your_username,your_mobile,referral_name,referral_contact,referral_email,
loan_type,loan_amount FROM mytable WHERE your_username = ? ");
$stmt->bind_param("s",$your_username);
I am using php with mysql database to do some insert.
I have 2 tables.
user
status
where the second table has as foreign key user_id to relate between these 2 tables
my problem is that when i insert into status table the user_id field do change and take 0 no matter what is the user_id.
so how to fix this problem ???
this is the code of login.php
<?php
//array for JSON response
$response = array();
// check for required fields
if(empty($_POST['user']) || empty($_POST['password'])){
$response["success"] = 0;
$response["message"] = "enter Both Fields";
// echoing JSON response
die (json_encode($response));
}
else if (isset($_POST['user']) && isset($_POST['password']) ) {
$user = $_POST['user'];
$password = $_POST['password'];
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$sql = mysql_query("Select user, password from users where user='$user'")or die(mysql_error());
$count_query = mysql_num_rows($sql);
if($count_query >0){
$response["success"] = 1;
$response["message"] = "correct Informations";
// echoing JSON response
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "Wrong User Or Pass";
// echoing JSON response
echo json_encode($response);
}
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
status.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
if(empty($_POST['status'])){
$response["success"] = 0;
$response["message"] = "You must Write something";
// echoing JSON response
die (json_encode($response));
}
// check for required fields
else if (isset($_POST['status'])) {
$status = $_POST['status'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO status(status, user_id) VALUES('$status' , '$last_insert_id')") or die(mysql_error);
$last_insert_id = mysql_insert_id();
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Your Status has been saved.";
// echoing JSON response
die (json_encode($response));
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
die (json_encode($response));
}
}
?>
i am using php with android so their is no html form
You can't. mysql_insert_id() only applies to the LAST insert performed. If you're doing two inserts, and call insert_id() after the second one, the first ID is lost.
There is no way around this.
You must have something like:
INSERT INTO foo ....
$fooid = mysql_insert_id();
INSERT INTO bar .... foo_id=$fooid
$barid = mysql_insert_id();
Given that your code actually seems to be split into multiple pages, it's even worse. mysql_insert_id() only applies to the CURRENT connection to the database. Once your first script exits, the connection is closed and the insert_id is lost.
The next script will get a NEW connection, and have its own completely separate insert_id system going.
For chaining multiple pages together like this, you'll have to retrieve/pass the insert ID around yourself, e.g.
page1:
INSERT ...
$_SESSION['page1_id'] = mysql_insert_id();
page2:
$last_id = $_SESSION['page1_id'];
INSERT ..... id=$last_id
I have this class am using to perform queries - insert, delete, drop create etc, but this time i created a method to update a table when the update have been submitted and to my surprise and hours of headache it is return success but not actually updating the record in the database am so confused, I have been debugging for hours to no avail
so i decided to share my worries to see if i can receive help as am actually 2 weeks old In OOP PHP
so here my class
class queryClass extends MYSQL{ //MYSQL is for connecting to database
//table fields
var $user_table = ''; //table names that will be used in all names, each query method will input its own table name
//connect to database
function dbconnect(){
MYSQL::dbconnect();
}
//prevent injection
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via qry function that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
//quote form
function quoteEditorform($formname, $formclass, $formaction, $helptext, $first, $second){
//conect to DB
$this->dbconnect();
echo"
<form name=\"$formname\" method=\"post\" id=\"$formname\" class=\"$formclass\" enctype=\"application/x-www-form-urlencoded\" action=\"$formaction\">
<h2>$helptext</h2>
<div><label for=qoute>NGWA QUOTE
<input type=button value='Quote' onclick=\"wrapInTags(this.form.message1,'quote')\">insert [quote].[/quote]tags
</label>
<textarea name=\"message1\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$first</textarea><br>
</div>
<div><label for=\"qoute\">ENGLISH MEANING
<input type=button value='Meaning' onclick=\"wrapInTags(this.form.message2,'meaning')\">
insert [meaning].[/meaning]tags
</label>
".$record['meaning']."
<textarea name=\"message2\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$second</textarea></div>
<input name=\"action\" id=\"action\" value=\"sendeditedquote\" type=\"hidden\">
<div>
<input name=\"submit\" id=\"submitV value=\"Save\" type=\"submit\"></div>
</form>
<div align=\"center\">Read Before Posting</div>
"; }
function createquotetable($tablename){
//connect to DB
$this->dbconnect();
$qry = "CREATE TABLE IF NOT EXISTS ".$tablename."(
quote_id INT(8) NOT NULL AUTO_INCREMENT,
ngwaquote TEXT NOT NULL,
meaning TEXT NOT NULL,
saved_date date,
PRIMARY KEY (quote_id)
) TYPE=INNODB
";
$result = $this->qry($qry);
return;
}
here's my quote-editor.html after including my class files
// instantiate all other needed classes
$cleaner = new cleanPost();
$connect = new MySQL();
$connect->dbconnect();// connect to a database
$bbcode = new BBCode();
$log = new logmein();
if($_REQUEST['action'] == "sendeditedquote"){
//post all the values to the database using our main class
/*topic field checking */
if($_REQUEST['message1'] == "" || $_REQUEST['topic'] > 600) {
$errmsg_arr[] = 'Sorry You Can\'t Send An Empty Qoute OR quote greater than 500 characters at a time';
$errflag = true;
}
if($_REQUEST['message2'] == "" ) {
$errmsg_arr[] = 'Sorry You Can\'t Update With An Empty Qoute';
$errflag = true;
}
//If there are input validations, redirect back
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: edit_quotes.html");
exit();
}
$log->updatequote("quotes", $_REQUEST['message1'], $_REQUEST['message2'], "quote_id", "ngwaquote", "meaning", $cleaner->clean($_GET['quote_id']));
}
ai'ght when i perform the query the success/error line returns that the update was successful but on the other page where i display all available quotes the particular quote still is NOT updated
Anyone who's experienced such please tell me what am gon' do.
BEING ASKED THE LINE FOR THE RAW QUERY
HERE IS IT-
first is the the method that cleanse ouy my post and the I use it for query using $this->qry(somequeries here)
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function using $this->qry()
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via ****qry function**** that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
If the where clause of your update statement does not match any rows, the update statement will return success.
However it will not change anything.
Note that MySQL knows when a value has not really changed so the statement
UPDATE table1 SET col1 = 0 WHERE col1 = 0
Will always return 0 for the number of affected rows.
If you want to know if anything has been changed you need to call:
$rows_updated = mysql_affected_rows($this->connection);
or
$rows_updated = mysqli_affected_rows($this->connection); //if you're using mysqli
An update statement will only indicate failure is an error has occured.
A warning about SQL-injection
I notice that you use dynamic table and column names.
If those values are in any way alterable by a user or pass through superglobals that can be affected by another php session that can be affected by a user, you have an SQL-injection hole.
Here's how to secure yourself against that: How to prevent SQL injection with dynamic tablenames?
I think i have found the answer to my problem
In the place i had the $this->quote_id i later figured out that the page editor url was editor.html?quote_id=1
then when I submitted it will now process the form on a flat url === editor.html so my mistake was that I didn't request for the QUOTE ID when i was still on the editing url editor.html?quote_id=1 instead requesting for it when it was not possible ie in editor.html so it was meant to return empty quote id which i used to update thereby resulting in update success but not really updating anything
so
all I did was add an input tag hidden to get the quote_id being edited and then post it along with the rest of the form
So simple but took me me hours of rereading and re coding, wonderful,
small things cause much frustration
Thanks all
if the fields you are updating is not the same has the fields in the database, it will not update. although it return success simple means that it sees the table and connect to the database