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
Related
I am making a php project and I am currently hosted it in my local xammp server.
I need to connect this to an android application using volley library.
So I need to make a json object.In orders I have stored picture of the product and orders.php page that I retrieve it via orderno.
In orders.php page I can see all my orders with images.
When trying to make the json object I need get this image url.I try to get it via order no but all the times i can't get the correct url.
Can anyone tell me how to solve this?
This is for making that json object.
This is the link to the image current json which I got
I want to make my image URL like below image:
There were multiple issues with your PHP code. However, I tried the resolve most of them. Still if you see any issues let me know, I will try to help you. I will highlight the changes I did to the code, for you to understand.
Here goes the PHP code to retrieve values:
<?php
// array for JSON response
$response = array();
include("config.php");
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die(mysqli_error());
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error());
$result = mysqli_query($con,"SELECT * FROM ORDERS");
if (!empty($result)) {
// check for empty result
if (mysqli_num_rows($result) > 0) {
// user node
$response["orderdata"] = array();
while($row = mysqli_fetch_array($result))
{
$orderdata = array();
$i = $row["ITEM_ID"];
$url = "http://localhost/Online_shopping/admin/'$i'.jpg";
$orderdata["url"] = $url;
$orderdata["item_id"] = $row["ITEM_ID"];
$orderdata["price"] = $row["PRICE"];
$orderdata["size"] = $row["SIZE"];
array_push($response["orderdata"], $orderdata);
}
// success
$response["response_code"] = 200;
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["response_code"] = 999;
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["response_code"] = 999;
// echo no users JSON
echo json_encode($response);
}
?>
You need to first setup a connection with your database which is located in a particular server.
Using that connection, you need to query in your table to get the data.
mysql_query, mysql_fetch_array is deprecated. You have to use mysqli instead of mysql.
Lastly, you can go through this post to learn simple basic operations using 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 am a newbie in here and i have a problem that me myself cannot find the exact solution... here it is... i need to build a system that will update all the staff information. through this system, a staff in human resource department will enter all the staffs information. i have been create this code to update the staffs information but it seems not function with what i really want.... i just want to update by rows however, it turns to update all rows in the database...
<?php
session_start();
include ("includes/database.php");
include ("includes/security.php");
include ("includes/config.php");
$nama=$_SESSION["nama"];
$pwd=$_SESSION["status"];
$nama=$_POST["st_nama"];
$siri1=$_POST["st_siri"];
$siri2=$_POST["st_siri2"];
$siri3=$_POST["st_siri3"];
$jawatan=$_POST["st_jawatan"];
$gred=$_POST["st_gred"];
$gredh=$_POST["st_gredh"];
$gelaran=$_POST["st_gelaran"];
$elaun=$_POST["st_elaun"];
$id=$_GET["id"];
$dataPengguna2= mysql_query("SELECT * FROM tbl_rekod where id='$id'");
mysql_query("UPDATE tbl_rekod set st_nama='$nama', st_siri='$siri1', st_siri2='$siri2', st_siri3='$siri3', st_jawatan='$jawatan', st_gred='$gred', st_gredh='$gredh', st_gelaran='$gelaran', st_elaun='$elaun' WHERE id='$id'") or die (mysql_error());
$status = "REKOD BERJAYA DIKEMASKINI!<br/><a href = 'stafflogin.php'><strong>KEMBALI KE LAMAN UTAMA</strong></a>";
?>
This will help fix your sql injection issue, and may also fix update 1 vs multiple rows issue. This method uses the PDO library in PHP. You can see more info on using PDO on the PHP site. It replaces the mysql_ set of commands which are no longer included in the PHP releases.
// Below replaces the mysql_connect() so it requires db credentials filled in
try {
$host = 'hostname';
$db = 'databasename';
$user = 'username';
$pass = 'password';
$con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
// This replaces the die("error message") potion of a mysql_connect() set-up
catch (Exception $e) {
$_errors['connect']['message'] = $e->getMessage();
$_errors['connect']['error_code'] = $e->getCode();
}
$nama = $_SESSION["nama"];
$pwd = $_SESSION["status"];
$nama = $_POST["st_nama"];
$siri1 = $_POST["st_siri"];
$siri2 = $_POST["st_siri2"];
$siri3 = $_POST["st_siri3"];
$jawatan = $_POST["st_jawatan"];
$gred = $_POST["st_gred"];
$gredh = $_POST["st_gredh"];
$gelaran = $_POST["st_gelaran"];
$elaun = $_POST["st_elaun"];
$id = $_GET["id"];
// You should do just a preliminary check that the id is a numeric value
// No sense in continuing if someone tries to foil the natural
// order of your code
if(is_numeric($id)) {
// The next 3 lines would be equivalent to the mysql_query("statement here")
// as well as a more robust version of mysql_real_escape_string(). It does more,
// but for sake of explanation it does that and more.
$dataPengguna2 = $con->prepare("SELECT * FROM tbl_rekod where id=:id");
// Binding paramaters basically sanitizes the value being inserted into your query
$dataPengguna2->bindParam(':id',$id);
$dataPengguna2->execute();
// There is no indication of what you are doing with the select above
// Set up the update statement
$query = $con->prepare("UPDATE tbl_rekod set st_nama=:st_nama, st_siri=:st_siri, st_siri2=:st_siri2, st_siri3=:st_siri3, st_jawatan=:st_jawatan, st_gred=:st_gred, st_gredh=:st_gredh, st_gelaran=:st_gelaran, st_elaun=:st_elaun WHERE id=:id");
// Bind all the values to sanitize against injection
// You could do a function that loops through an array of values,
// but this is one way to do it manually
$query->bindParam(':st_nama',$nama);
$query->bindParam(':st_siri',$siri1);
$query->bindParam(':st_siri2',$siri2);
$query->bindParam(':st_siri3',$siri3);
$query->bindParam(':st_jawatan',$jawatan);
$query->bindParam(':st_gred',$gred);
$query->bindParam(':st_gredh',$gredh);
$query->bindParam(':st_gelaran',$gelaran);
$query->bindParam(':st_elaun',$elaun);
$query->bindParam(':id',$id);
$query->execute();
// Print out error info. There may be something of value here
// that may help you figure out why it's trying to update all your rows
// instead of just the one.
print_r($query->errorInfo());
$status = "REKOD BERJAYA DIKEMASKINI!<br/><a href = 'stafflogin.php'><strong>KEMBALI KE LAMAN UTAMA</strong></a>";
} ?>
I am making an iphone app. a part of that app allows users to search for a company on location.
I have a MySql database containing the companies that can be searched for, and a php file on my website to receive the searched data, and to return the companyName and companyLocation for all the found companies to my app. it looks like this:
<?php
if (isset($_GET["companyCitySearchField"])){
$companyCity = $_GET["companyCitySearchField"];
$result = search($companyCity);
echo $result;
}
function makeSqlConnection()
{
$DB_HostName = "******";
$DB_Name = "*******";
$DB_User = "*******";
$DB_Pass = "*******";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
return $con;
}
function disconnectSqlConnection($con)
{
mysql_close($con);
}
function search($companyCity)
{
$con = makeSqlConnection();
$query = mysql_query("SELECT companyName, companyCity from Company WHERE companyCity = '$companyCity'");
$companies = array();
while ($row = mysql_fetch_assoc($query)) {
$companies['companies'][] = $row;
print json_encode($companies);
}
disconnectSqlConnection($con);
}
?>
this works fine when only one company is found. it gives me a perfect JSON array:
{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"}]}
everything fine so far.
Now, I create another company in my database, also with Geldermalsen as location.
2 companies are found in the database now. the JSON array it return now, doesn't make sense:
{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"}]}{"companies":[{"companyName":"Dijkstra","companyCity":"Geldermalsen"},{"companyName":"testaccount","companyCity":"Geldermalsen"}]}
for some reason, it seems to make 2 separate array's. one for the first found company, and one with both.
I have been searching the web, stackoverflow, google and even the book 'PHP and MySql for dummies' for days, and I have changed my code numerous times, and whatever I try it keeps on doing this.
Does anyone know what I should do to get one array containing all found companies with this script, instead of these 2?
any help would be very welcome, Thank you in advance!
You are echoing out JSON for each row, not for the fully built array. Move your print statement outside the loop.
$companies = array();
while ($row = mysql_fetch_assoc($query)) {
$companies['companies'][] = $row;
}
print json_encode($companies);
Or better yet, you might not want to echo out anything at all in the search function, but leave that up to the caller. It seems you already might be intending to do this here:
$result = search($companyCity);
echo $result;
The only problem is that the search() function doesn't return any value so $result would be null. You should make up your mind about where you are going to echo the result to the client and be consistent about it.
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.