Basically I am trying to use PHP to update MySQL database and I am testing it with an HTML form.
I intend to use this in an android app so that is where the values will be taken from but currently I am just testing with a HTML form to test the PHP code. When I am testing with the HTML form the appropriate data is not being updated currently.
What is wrong with my code that causes this?
PHP code:
/*
* Following code will create a new product row
* All player details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['PlayerID']) && isset($_POST['Score']) && isset($_POST['LastHolePlayed'])&&
isset($_POST['Overall'])) {
$playerid = $_POST['PlayerID'];
$score = $_POST['Score'];
$lastholeplayed = $_POST['LastHolePlayed'];
$overall = $_POST['Overall'];
// include db connect class
require('db_connection.php');
// mysql inserting a new row
$result = mysql_query("UPDATE `week1` SET Score = `$score`, LastHolePlayed = `$lastholeplayed`,
Overall` = $overall` WHERE PlayerID = `$playerid`");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Player successfully added.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "An error occurred.";
// 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);
}
html code:
<form action="http://localhost/realdeal/updateplayer.php" method="POST">
PlayerID <input type="text" id='PlayerID' name='PlayerID'><br/><br/>
Score <input type="text" id='Score' name='Score'><br/><br/>
LastHolePlayed <input type="text" id='LastHolePlayed' name='LastHolePlayed'><br/><br/>
Overall <input type="text" id='Overall' name='Overall'><br/><br/>
<input type="submit" value="submit">
</form>
change your query to:
$result = mysql_query("UPDATE `week1` SET `Score` = '$score', `LastHolePlayed` = '$lastholeplayed', `Overall` = '$overall' WHERE `PlayerID` = '$playerid'");
Your query delimiters need to be corrected:
$result = mysql_query("UPDATE `week1` SET Score = '$score', `LastHolePlayed` = '$lastholeplayed', `Overall` = '$overall' WHERE `PlayerID` = '$playerid'");
Notice the backticks (`) around column and table names and single quotes (') around the values.
Also, when you are debugging a query, always check for MySQL errors:
$result mysql_query(...) or die("Query failed: " . mysql_error() );
Finally, you should know that your query leaves you open to SQL injection attacks. Always clean your input data before including it in a query.
Your sql statement is wrong. You can write as stated above or you can directly write the statement without any apostrophe symbol as -
$result = mysql_query("UPDATE week1 SET Score=$score, LastHolePlayed=$lastholeplayed, Overall=$overall WHERE PlayerID=$playerid");
Moreover, can you explain what do you mean by "appropriate data is not being updated". It would be more clear if you give/state the error you are getting.
Related
I want to test if user enter incorrect file number and ic, the message "Inccorect ref no and ic no" will shown, but it didn't work like that. It always shown the message "Thanks you for register attendance with us." Help me please..I'm new.
<?php
require "init.php";
$file_number = $_POST["file_number"];
$ic_no = $_POST["ic_no"];
$attendance = $_POST["attendance"];
//$ic_no = $_REQUEST['ic_no'];
$sql = "INSERT INTO reg_attend(file_number,ic_no,attendance) SELECT reg_meeting.file_number,reg_staff.ic_no,'".$attendance."' FROM reg_meeting,reg_staff WHERE (reg_meeting.file_number = '".$file_number."' AND reg_staff.ic_no = '".$ic_no."')";
$result = mysqli_query($conn,$sql);
$response = array();
if($result)
{
//var_dump($result);
$code = "reg_success";
$message = "Thanks you for register attendance with us.";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode($response);
}
else
{
$code = "reg_failed";
$message = "Incorrect REF No. and IC No.";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode($response);;
}
mysqli_close($conn);
?>
You need to validate your incoming data before you insert into your DB. It looks like currently, you will be inserting empty values into your reg_attend table. As this is likely successful, you will not be reaching the else.
If you need to validate that the passed in data exists, do a select first e.g.
SELECT reg_meeting.file_number,reg_staff.ic_no,'".$attendance."' FROM reg_meeting,reg_staff WHERE (reg_meeting.file_number = '".$file_number."' AND reg_staff.ic_no = '".$ic_no."')"
then check the results of that, before inserting.
As a side note, please please DO NOT use this code as shown. You should prefer to use query parameters with either PDO or mysqli. See https://www.php.net/manual/en/pdo.prepare.php
I am sending data from my android app to be added to the online database. But the data does not gets stored at end of table. It gets stored at random position in table. How do I avoid this? here is my php code.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$response = array();
$title = $_POST['Title'];
$time = $_POST['Time'];
$posted= $_POST['posted'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("INSERT INTO mukul(Title, Time, posted) VALUES('$title', '$time', '$posted')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
?>
There's no such thing as an "end of a table" in relational databases. The data is stored in whatever order is most convenient for the database (which is affected by the indexes on the table). So what you're asking about is not a bug at all but expected behavior. Just use the ORDER BY clause when fetching the data to ensure the order you want. Contrary to what you may believe (I have to guess since question is a bit vague), doing an ORDER BY is not a slow operation, especially if you have an index on the sorted column(s).
If you need help with indexes, the MySQL manual has you covered.
I want to update information. when I use the below in code is not working what is wrong in my code:
if(isset($_POST['submit'])){
$sql = "UPDATE `food`.`food_item`
SET `food_name` = '$_POST[food_name]',
`food_price` = '$_POST[food_price]',
`food_cat` = '$_POST[food_category]'
WHERE `food_item`.`id` ='$_POST[id]';";
$result = mysql_query($sql) or die("query not");
header("Location: product_info.php") ;
}
If you have a form input like,
<input type="text" name="product_name" />
You should get the value by,
$_POST['product_name'];
Is your form method is POST for GET?
If your method type is POST, you should get it like $_POST['input_name']
If your method type is GET, you should get it like $_GET['input_name']
Does all your input name you mentioned in html matches in php code?
Eg : If you have a form with input type,
<input type="text" name="product_name" />
Then, in php code, you should get it with what you entered in name attribute
$_POST['product_name'] OR $_GET['product_name']
Not something like,
$_POST['prod_name'] OR $_GET['prod_name']
Try this,
if(isset($_POST['submit'])
{
$food_name = $_POST['food_name'];
$food_price = $_POST['food_price'];
$food_cat = $_POST['food_category'];
$id = $_POST['id'];
// do not directly input the form data to sql, filter it by a special function mysqli_real_escape_string
// eg : $food_price = mysqli_real_escape_string($db, $_POST['food_price']);
// before executing the query, try to echo the each form input and sql query for clear picture.
$sql = "UPDATE `food`.`food_item` SET `food_name` = '$food_name',`food_price` = '$food_price',`food_cat` = '$food_cat' WHERE `food_item`.`id` ='$id'";
$result = mysqli_query($db, $sql);
if($result)
{
//header("Location: product_info.php") ;
echo "success";
}
else
{
echo "fail";
}
}
else
{
echo "form not submitted";
// use header to redirect to old page again
}
WARNING :
mysql is deprecated. Use mysqli or PDO.
Note :
$db is a database connection variable. You need to setup like
$db = mysqli_connect("localhost","username","password","database_name");
Look it's not mysql_connect, its mysqli_connect. Replace the db value according to your needs.
You can try following code to find the error.
echo mysql_error(); exit;
after following code.
$result = mysql_query($sql)
In order to access the array variables inside double quoted string, either do by enclosing them in curly brackets or put it outside the double quotes and append as a string. Here you try adding curly brackets like this:
if(isset($_POST['submit'])){
$sql = "UPDATE `food`.`food_item`
SET `food_name` = '{$_POST['food_name']}',
`food_price` = '{$_POST['food_price']}',
`food_cat` = '{$_POST['food_category']}'
WHERE `food_item`.`id` ='{$_POST['id']}';";
$result = mysql_query($sql) or die("query not");
header("Location: product_info.php") ;
}
Just echo $sql; Check what are the actual values in the query. Copy & run it in MYSQL query.
I think that you applied back ticks () on field names food_name . Remove back ticks & replace it with single quote ( ' )
I am trying to get the two values from my application in my php code. but before doing it I am trying to check through URL. But my problem is if give the values manual I am getting right output but when I check it by passing the values I am getting an syntax error. Can any one help me in solving this.
<?php
$hostname_localhost ="localhost";
$database_localhost ="mobiledb";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
$response = array();
mysql_select_db($database_localhost, $localhost);
$day = $_POST['day'];
$Q = $_POST['Qno'];
// get a product from products table
$result = mysql_query("SELECT $Q FROM `Questions` WHERE `day`='$day'") or die(mysql_error());
//echo $result;
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["question"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["question".$i] = $row["$Q"];
$i = $i + 1;
// push single product into final response array
array_push($response["question"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No users found";
// echo no users JSON
echo json_encode($response);
}
?>
I am trying to check through URL
By this I assume you mean you are trying to go to the url:
http://localhost/yoursite/yourpage?Qno=5&day=thing
In that case, those variables will be accessed as $_GET['Qno'] and $_GET['day'].
You can use $_REQUEST['Qno'] and $_REQUEST['day'] to receive the variables both ways. Of course, your application has so many security holes I won't even touch.
I would try escaping your values. will possibly fix your error and also protect you somewhat from SQL Injection which you should google and read.
$day = mysql_real_escape_string($_GET['day']);
$Q = mysql_real_escape_string($_GET['Qno']);
In this example, we use $_GET because you are trying to obtain the value directly from the URL.
Also, we escape the string to make sure we don't break our string syntax and inject bad monsters into your database!
ALSO: Mysql_ functionality is discontinued and you should stop using it. Read the big red box here: http://php.net/manual/en/function.mysql-query.php
I have some PHP code to select data from & insert data into a MYSQL database.
Here's what I'm trying to do:
- receive a barcode serial number from a JSON payload
- connect to the MySQL database
- check a database table (passes) to see if the barcode has been registered
- if so, write this barcode + timestamp into another table (activations). Then return a JSON mssage that it was successful
- if not, return a JSON message that the barcode was not yet registered.
The code below works OK when I check a specific barcode for the first time. But after that it doesn't insert a new entry in the activations table. Instead I get the message 'Activation not recorded' ..
Any idea what I'm doing wrong?
Thanks if you can help!
Andrew
<?php
//Messages will be returned as JSON data
header("Content-type: application/json");
//read the POST payload
$payload = json_decode(file_get_contents('php://input'), true);
//get a database connection
require_once("../class/Database.php");
$db = Database::get();
//check for a valid pass
$barcode = $payload['barcode'];
$statement = $db->prepare("SELECT * FROM passes WHERE barcode = ?");
$statement->execute(array($barcode));
$row = $statement->fetch(PDO::FETCH_ASSOC);
if ($row) {
$statement2 = $db->prepare("INSERT INTO activations(activationDatetime, barcode) VALUES (?,?)");
$statement2->execute(array(date("Y-m-d G:i:s"),$barcode));
if ($statement2->rowCount()==0) {
print json_encode(array("msg"=>"Activation not recorded"));
} else {
print json_encode(array("msg"=>"Pass successfully activated"));
}
} else
{
print json_encode(array("msg"=>"Pass not registered"));
exit();
}
flush();
exit();
?>
I guess if ($statement2->rowCount()==0) { this statement is wrong please check. You can not use "rowCount" there as it is a insert query.
And I think, it is inserted only issue is not showing message properly.
You should print the sql error at the debug stage of your page.
I guess, the barcode field is uniq.