Items does not get inserted at end of SQL table android - 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.

Related

PHP login script using bind_result in subsequent query mysqli

I'm trying to build a relatively simple PHP login script to connect to MySQL database running on my home server. I know the connection works as I've gotten some data returned as I would expect. However, I am having trouble getting the full script to work.
Essentially, I'm taking in a username/password from the user, and I first do a lookup to get the user_id from the users table. I then want to use that user_id value to do a comparison from user_pswd table (i'm storing usernames and passwords in separate database tables). At one point, I was able to echo the correct user_id based on the username input. But I haven't been able to get all the issues worked out, as I'm pretty new to PHP and don't really know where to see errors since I load this onto my server from a remote desktop. Can anyone offer some advice/corrections to my code?
The end result is I want to send the user to another page, but the echo "test" is just to see if I can get this much working. Thanks so much for the help!
<?php
ob_start();
$con = new mysqli("localhost","username","password","database");
// check connection
if (mysqli_connect_errno()) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$users_name = $_POST['user'];
$users_pass = $_POST['pass'];
$user_esc = $con->real_escape_string($users_name);
$pass_esc = $con->real_escape_string($users_pass);
$query1 = "SELECT user_id FROM users WHERE username = ?;";
if ($result1 = $con->prepare($query1)) {
$result1->bind_param("s",$user_esc);
$result1->execute();
$result1->bind_result($userid);
$result1->fetch();
$query2 = "SELECT user_pswd_id FROM user_pswd WHERE active = 1 AND user_id = ? AND user_pswd = ?;";
if ($result2 = $con->prepare($query2)) {
$result2->bind_param("is",$userid,$pass_esc);
$result2->execute();
$result2->bind_result($userpswd);
$result2->fetch();
echo "test", $userpswd;
$result2->free_result();
$result2->close();
} else {
echo "failed password";
}
$result1->free_result();
$result1->close();
}
$con->close();
ob_end_clean();
?>

Data Management Issue - How to manage retrieved data from mysql?

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.

Getting a SQL syntax error

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

Updating MySQL database with PHP

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.

PHP/MySQL code fail to insert duplicate row

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.

Categories