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.
Related
I am developing a game(c#) with database(mysql) and web service(php) to retrieving the data. The issue is the data management. There is a table on database with the name of items and it has some columns like id, item_name, item_description, item_prop, update_date, ownerId. I added 70 items to this table manually. The users can also add some items to this table or they can update the items they have already added in the game. My purpose is retrieving the whole affected rows of the table when the user is first logged in and save it as a json file in the game folder. After, read that file to fill the game environment with those items.
I try a way to achieve this. Firstly, i hold an updateDate variable in the game which is past like "1990-05-10 21:15:43". Second, i send this variable to the webservice as '$lastUpdateDate'; and make a query according to that variable at the database. select * from channels where update_date >= '$lastUpdateDate'; and write these rows in a json file as items.json. after that make a second query to retrieve the time and refresh the updateDate variable in the game. select select now() as 'Result';. In this way user would not have to get the whole table and write in json file every login process. So, it would be good for the performance and the internet usage. The problem occurs when the users update an item which is already added before. I can see the updated item, too with the first query, but I wrote it in json file twice in this way.
php code part of the getItems of my loginuser.php :
<?php
include './function.php';
// CONNECTIONS =========================================================
$host = "localhost"; //put your host here
$user = "root"; //in general is root
$password = ""; //use your password here
$dbname = "yourDataBaseName"; //your database
$phpHash = "yourHashCode"; // same code in here as in your Unity game
mysql_connect($host, $user, $password) or die("Cant connect into database");
mysql_select_db($dbname)or die("Cant connect into database");
$op = anti_injection_register($_REQUEST["op"]);
$unityHash = anti_injection_register($_REQUEST["myform_hash"]);
if ($unityHash == $phpHash)
{
if($op == "getItems")
{
$lastUpdateDate = anti_injection_login($_POST["updateDate"]);
if(!$lastUpdateDate)
{
echo "Empty";
}
else
{
$q = "select * from items where update_date >= '$lastUpdateDate';";
$rs = mysql_query($q);
if (!$rs)
{
echo "Could not successfully run query ($q) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($rs) == 0)
{
echo "No rows found, nothing to print so am exiting";
exit;
}
$arr = array();
while ($row = mysql_fetch_row($rs))
{
$arr = $row;
}
echo json_encode($arr);
}
mysql_close();
}
}
?>
So, how can i solve this problem? Or do you have any better idea for this approach. Help would be much appreciated. Thank you for your time.
When I send my content from my frontend it successfully reaches my if (!empty)-statement but the table in my phpmyadmin/mysql-database does not recieve the information and does not add it.
I have two tables. One varchar (text) named "photo" and a ID called "id" which is A_I.
With my current code I only send (well attempt to send) the text about "photo" but nothing about the ID as it is A_I? Maybe I need to add some addiotional code to that as well and that might be the issue here and the reason the database does not seem to add the content that I send?
<?php
$value = json_decode(file_get_contents('php://input'));
$mysql_pekare= new mysqli ("", "","", "");
if(!empty($value)) {
echo "You reached the IF-statement";
$stmt = $mysql_pekare->prepare("INSERT INTO photoAlbum(`photo`) VALUES(?)");
$stmt->bind_param("s", $value['photo']);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
}
?>
In my frontend when I send the content I recieve this in the log:
{"photo":"test"}
And I also recieve this in the log, the echo call I did if it reaches the IF function which it successfully does:
"You reached the IF-statement"
By default, json_decode() returns an object, so your value is in $value->photo.
So your INSERT code should be -
if(!empty($value)) {
echo "You reached the IF-statement";
$stmt = $mysql_pekare->prepare("INSERT INTO photoAlbum(`photo`) VALUES(?)");
$stmt->bind_param("s", $value->photo);
$stmt->execute();
$stmt->close();
$mysql_pekare->close();
}
you must put the value for mysqli constructor required like localhost or ip , username of database , password of your database and database name then it will work fine for Example:-
$mysql_pekare=new mysqli ("localhost", "username","password", "databasename");
I'm trying to check for an existing entry in MySQL before executing the INSERT statement. If the user enters a name already in the database (field is set to unique) then they should be prompted to re-enter the name.
The problem I'm having is that if the new entry matches a record in any form then the error message displays and no INSERT happens.
For example, if the user enters DUMMY_NEW and there is a record DUMMY_OLD they aren't able to add the record even though DUMMY_NEW does not exist in the table.
I've searched and tried other answers already but can't seem to get this to work.
Code with extraneous bits removed for clarity:
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Set variables according to user input on previous form
$Server_Name = $_POST['Server_Name'];
//Check for duplicate server name - if exists inform user else run INSERT ($stmt)
$checkdup = "SELECT * FROM dcr_table WHERE SERVER_NAME = '".$Server_Name."'";
$dupresult = $conn->query($checkdup);
if($dupresult = 1)
{
print "<br>Error! <p></p>";
echo "" . $Server_Name . " already exists in the DCR";
print "<p></p>Please check the Server Name and try again";
}
else {
//Define the INSERT statement
$stmt = "INSERT INTO dcr_master (Server_Name, Description,..., ... , ... )";
//Execute the INSERT statement
$conn->query($stmt);
//Success and return new id
echo "<br><p></p>Record Added!<p></p>";
echo "New id: " . mysqli_insert_id($conn);
//Drop the connection
$conn->close();
};
Edit:
I'm aware of the injection vulnerability. The MySQL account only has SELECT, INSERT and UPDATE rights to the table. The end user must supply the password or submit will fail. This is small app with limited user access at the moment. MySQL escape strings will be implemented after current issue is resolved.
Edit 2:
Using Hobo Sapiens method does work in reporting an existing entry however a new (empty) row is still added to the table. The record ID still auto-increments so what I get is id#300 - record, id#301 - blank, id#302 - record. Is this a result of the IGNORE in the INSERT statement?
Your code creates a race condition if two people attempt to create the same ame at the same time and you're not handling the fallout properly.
If you have set the SERVER_NAME column to UNIQUE then you needn't check for the existence of a server name before you perform your INSERT as MySQL will do that for you. Use INSERT IGNORE ad check the number of affected rows after the query has executed to find out if it worked:
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Set variables according to user input on previous form
$Server_Name = $_POST['Server_Name'];
//Define the INSERT statement with IGNORE keyword
$stmt = "INSERT IGNORE INTO dcr_master (Server_Name, Description,..., ... , ... )";
if ($conn->query($stmt) === false) {
die("Database error:".$conn->error);
}
// Check for success
if ($conn->affected_rows == 0) {
print "<br>Error! <p></p>";
echo "" . $Server_Name . " already exists in the DCR";
print "<p></p>Please check the Server Name and try again";
} else {
//Success and return new id
echo "<br><p></p>Record Added!<p></p>";
echo "New id: " . $conn->insert_id;
}
This is an atomic operation so no race condition, and it involves only one call to the database.
I recommend you use either the OOP style or the procedural style for mysqli_*() but don't mix them. Usual warnings about SQL injection apply.
Use mysqli_num_rows
$row_cnt = $dupresult->num_rows;
if ($row_cnt > 0) {
echo "There is a matching record";
}else {
//insert into table
}
This statement:
if($dupresult = 1)
will always return 1. You should first retrieve the first query result (if any), like so:
$row=$dupresult->fetch_array(MYSQLI_NUM);
and then compare the result against NULL:
if(!$row)
Please help i commented off some stuff for testing purposes but nothing works
<?php
//retrieve the data sent in the POST request
$yourDateOrdered =$_POST["DateOrdered"];
$yourDueDate = $_POST["DueDate"];
if(isset($_POST["CompanyName"])){$yourCompanyName = $_POST["CompanyName"];}
//Validate the fields
if ($yourDateOrdered=="" || $yourDateOrdered==null){
$err= $err."Please enter the date the purchase order was made<br>";
}
if ($yourDueDate=="" || $yourDueDate==null){
$err= $err. "Please enter a date when the item is required<br>";
}
//if ($yourCompanyName=="" || $yourCompanyName==null){
//$err= $err."Please enter the customer name<br>";
//}
//Connect to the server and select database
include("dbConnection.php");
//define sql query to execute on the database
$Query1="INSERT INTO orders(CompanyName, DateOrdered, DueDate)
VALUES ('$yourCompanyName','$yourDateOrdered', '$yourDueDate')";
//execute query
//$result = mysql_query($Query1);
//echo("The following order has been added");
//result of the action stored in $Result
$Result = mysql_query($Query1);
if($Result){
echo 'Order entered';
echo Header ("Location:orderformitem.php");
}
//Close the connection
mysql_close($con);
//Check if query executed successfully and forward the user to an appropriate location
//if($queryResult){
//echo "Order save <br>";
//Header ("Location:../PHP/orderformitem.php");
//}
?>
You definietly need to learn how to debug. First, comment out the Header('Location ...'); row, to catch errors.
add error_reporting(E_ALL); and display_errors(1); at top of your file, to see any errors.
Let's var_dump($_POST) to see, is all the variables are correct.
Do a date validation, if you are want correct dates.
Dump your query, and try to run it in sql directly.
DO NOT use mysql functions because they are deprecated. Use mysqli or PDO instead.
Escape your data, to avoid sql injections!
First off, just wanted to say I'm a novice at this type of coding, although I'm hopeful that I'll eventually make sense of it all with a little guidance.
I have a MySQL database table (promotion) that stores a bunch of redemption codes for various products (for a give away contest). The idea is, the first person to enter the redemption code wins the product, and their info should be stored in the "promotion" table.
The table's columns are: redeem_id (Auto Increment field), redeem_code, redeemer_email, redeemer_first_name, redeemer_last_name, and redeem_date_time.
Initially, the redeem_id and redeem_code fields are the only ones with any data. What I'd like to happen is when a user enters their information (name, email, etc) and submit a redemption code, their info will populate the rest of the row for that particular code. If anyone else tries to submit a code that has already been redeemed, they should receive an error message - likewise for an invalid code (i.e. a code that does not exist in the table).
The PHP code I have so far is:
<?php
function get_promotion_by_redeem_code($redeem_code)
{
$sql = "SELECT * FROM promotion WHERE redeem_code= '".mysql_real_escape_string($redeem_code)."'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row;
}
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).", redeemer_first_name=".mysql_real_escape_string($first_name).", redeemer_last_name=".mysql_real_escape_string($last_name).", redeem_date_time=NOW(), WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
$insert = mysql_query($query);
return $insert;
}
$email=$_POST['e_mail'];
$first_name=$_POST['f_name'];
$last_name=$_POST['l_name'];
$redeem_code=$_POST['v_code'];
$connection = mysql_connect('localhost', 'db', 'pw');
mysql_select_db('db', $connection);
$promotion = get_promotion_by_redeem_code($redeem_code);
if ($promotion) {
if (!$promotion['redeemer_email']) {
redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code);
echo 'Congratulations, you have successfully claimed this item!';
} else {
echo 'Sorry, this item has already been redeemed.';
}
} else {
echo 'Sorry, you have entered an incorrect claim code. Please use your browser\'s back button to try again.';
}
mysql_close($connection);
?>
It works as expected when I enter an invalid claim code, or if a code's row has been previously populated.
When it doesn't work, is when someone goes to redeem the item for the first time. Essentially, it will show the "Congratulations" message, however the table doesn't get updated for the submitted information. Therefore, no matter how many times the correct code is entered, the user will receive the "Congratulations" message.
I'm fairly certain that the error is in the redeem_promotion() function, but I can't figure out where.
You have add an extra comma(,) before WHERE clause. Thats the mistake, i think.
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).",
redeemer_first_name=".mysql_real_escape_string($first_name).",
redeemer_last_name=".mysql_real_escape_string($last_name).",
redeem_date_time=NOW()
WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
**OR**
$query = "UPDATE promotion
SET redeemer_email='".mysql_real_escape_string($email)."',
redeemer_first_name='".mysql_real_escape_string($first_name)."',
redeemer_last_name='".mysql_real_escape_string($last_name)."',
redeem_date_time=NOW()
WHERE redeem_code='".mysql_real_escape_string($redeem_code)."'";
$insert = mysql_query($query);
return $insert;
}