I am new to web design, and I'm using a very simple ajax method to get the id of a product from a database. Being so new to backend stuff, I was wondering if anyone wouldn't mind teaching me a little about php security.
My first area in question is the post method and the method in which i get the data for the post method.
function setupc(upc) {
var sku1 = $("#option1 option:selected").data('sku');
var sku2 = $("#option2 option:selected").data('sku');
if (sku2 !== null) {
upc = (sku1 + sku2);
} else {
upc = (sku1);
}
$('input[name="upc"]').val(upc);
$.post('getproduct.php', {upc: upc}, function(data){
$('.result').html(data);
});
}
And here is the getproduct.php
<?php
require_once("config.php");
$con=mysql_connect (MySQL, $username, $password);
if (!$con) {
die("Not connected : " . mysql_error());
}
$db = mysql_select_db($database, $con);
if (!$db) {
die ("Can\'t use db : " . mysql_error());
}
$upc = "$_POST[upc]";
$sql = "SELECT * FROM products WHERE upc = '$upc'";
$result = mysql_query($sql, $con) or die(mysql_error());
$row=mysql_fetch_array($result);
?>
<input type="hidden" id="id" name="id" value="<? echo $row['id']; ?>">
<input type="text" id="price" value="<? echo $row['price']; ?>">
<?php mysql_close($con); ?>
If this is not the place to ask these kinds of questions, please let me know and I'll gladly remove it. And, maybe even point me to a place that i can.
your code doesn't prevent so-called "SQL injection"
This means that someone can call your script with sql-statements in the
$_POST['upc'] parameter
Your query would be better using mysql_real_escape_string:
$sql = "SELECT * FROM products WHERE upc = '" . mysql_real_escape_string($upc) . "'";
any sql code would be escaped and won't be executed.
EDIT: you also may google for "SQL injection" a little bit, to learn about this security matter
Related
Can I please have some help with a problem I'm having updating a mysql database with PHP.
I'm sorry to ask a question that has been asked a lot of times before, it's just driving me a bit nuts, and I've looked through similar questions but the answers don't seem to help with my problem.
I'm using two files, an admin page (admin.php) to edit content with, and an update file that is meant to update the database when the submit button is pressed.
Everything seems to be working fine, the values are being posted to the update.php page (I can see them when I echo them out) but it wont update the database.
If anyone can please point me in the right direction or tell me what I'm doing wrong I'd be very grateful!
Thank you very much:)
This is my admin.php page;
<head>
<?php
/*
Check to see if the page id has been set in the url.
If it has, set it as the $pageid variable,
If it hasn't, set the $pageid variable to 1 (Home page)
*/
if (isset($_GET['pageid'])) {
$pageid = $_GET['pageid'];
}
else {
$pageid = '1';
}
//Database connection variables
$servername = "localhost";
$username = "root";
$password = "";
$database = "cms";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Get information from the database
$sql = "SELECT title, sub_title, tab1, tab2, tab3, content FROM data WHERE id='$pageid'";
$result = $conn ->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$conn->close();
//Store database information in variables to display in the form
$title = $row["title"];
$sub_title = $row["sub_title"];
$tab1 = $row["tab1"];
$tab2 = $row["tab2"];
$tab3 = $row["tab3"];
$content = $row["content"];
}
} else {
echo "0 results";
}
?>
</head>
<body>
//basic navigation
Page 1 | Page 2 | Page 3
<form action="update.php" method="post" name="adminform">
<input type="hidden" name="pageid" value="<?php echo "$pageid";?>">
NAME:<br>
<input type="text" name="title" value="<?php echo $title;?>"><br><br>
EMAIL:<br>
<input type="text" name="sub_title" value="<?php echo $sub_title;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab1" value="<?php echo $tab1;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab2" value="<?php echo $tab2;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab3" value="<?php echo $tab3;?>"><br><br>
CONTENT:<br>
<textarea rows="4" cols="50" name="content">
<?php echo $content;?>
</textarea>
<br><br>
<input type="submit">
</form>
</body>
And this is the update.php page;
<?php
/*Values passed from the admin form, to be used as update variables*/
if (isset($_POST['adminform']))
{
$pageid = $_POST["pageid"];
$titleu = $_POST["title"];
$sub_titleu = $_POST["sub_title"];
$tab1u = $_POST["tab1"];
$tab2u = $_POST["tab2"];
$tab3u = $_POST["tab3"];
$contentu = $_POST["content"];
}
?>
<?php
if(isset($_POST['adminform']))
{
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Update the database
$sql = "UPDATE data SET title='$titleu', sub_title='$sub_titleu', tab1='$tab1u', tab2='$tab2u', tab3='$tab3u', content='$contentu' WHERE id =='$pageid'";
$result = $conn ->query($sql);
$conn->close();
}
?>
You're using == instead of = on the where clause.
On the other hand, don't pass user values to the query without validation and sanitization if you don't want to be vulnerable to sql injection attacks.
$sql = "UPDATE data SET title='" . $conn->real_escape_string($titleu) . "', sub_title='" . $conn->real_escape_string($sub_titleu) . "', tab1='" . $conn->real_escape_string($tab1u) . "', tab2='" . $conn->real_escape_string($tab2u) . "', tab3='" . $conn->real_escape_string($tab3u) . "', content='" . $conn->real_escape_string($contentu) . "' WHERE id = " . (int)$pageid;
This will work, but is not very elegant solution. You may use prepared statements instead, to pass the correct types and prevent sql injection.
Check your DB Connections and test whether you are connected to DB or not.
Change your query as below
$sql = "UPDATE data SET title='".$titleu."', sub_title='".$sub_titleu."', tab1='".$tab1u."', tab2='".$tab2u."', tab3='".$tab3u."', content='".$contentu."' WHERE id ='$pageid'";
I'm working on a very basic PHP programme. I'm very new to PHP and am aware that I'm using the older versions i.e not PDO. I've been working on this for a while and can't figure out why it isn't working.
I'm simply trying to delete an item from my table which matches the user input.
((also if anyone has any easy recommendations I can use to have a safer delete function as I am aware if the user input is 'r' for example, a huge chunk of the table will be deleted))
Here is my code:
<?php
//delete from table
if(isset($_POST['delete1']))
{
$deletevalue = $_POST['deletevalue'];
$deletequery = "DELETE FROM users WHERE deletevalue = $deletevalue";
$deleteresult = deleteTable($deletevalue);
}
function deleteTable ($deletevalue)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$delete_fromTable = mysqli_query($connect, $deletevalue);
print mysqli_error($connect);
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="zzz.php" method="post" />
<p> Remove Item: <input type="text" name="deletevalue" placeholder="Item
Name" /> </p>
<input type="submit" name ="delete1" value="submit" />
</form>
</body>
</html>
regarding all comments, and completely OK with security statements, you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection. Plus : use error_reporting(E_ALL); ini_set('display_errors', 1); on top of your pages will help PHP give you hint about errors :)
This is a way (not the only one) to handle your query.
Please read carefully and adapt names according to your DB structure and column names.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */
/* store in PHP variable */
$deletevalue = $_POST['deletevalue'];
echo"[ is my var ok ? -> $deletevalue ]"; /* just checking value */
// connexion to db
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); }
$query = " DELETE FROM `users` WHERE deletevalue = ? ";
$stmt = $mysqli->prepare($query); /* prepare query */
$stmt->bind_param("s", $deletevalue); /* bind param will sanitize -> 's' is for a string */
print_r($stmt->error_list); /* any error ? */
print_r($stmt->get_warnings()); /* any error ? */
print_r($stmt->error); /* any error ? */
/* another ways of checking for errors :
if (!($stmt = $mysqli->prepare(" DELETE FROM `users` WHERE deletevalue = ? "))) {
echo "Error attempting to prepare : (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("s", $deletevalue)) {
echo "Error attempting to bind params : (" . $stmt->errno . ") " . $stmt->error;
}
*/
if (!$stmt->execute()) { echo"false"; echo "Error attempting to execute : (" . $stmt->errno . ") " . $stmt->error; } else { echo"true"; }
?>
Here your code will be looks like (Except security issue)
In this code you are deleting your record on the basis of firstName of the user thats why in where clause WHERE firstName = '$deletevalue' firtName there.
if(isset($_POST['delete1']))
{
$deletevalue = $_POST['deletevalue'];
//here put your table column in where clause
$deletequery = "DELETE FROM users WHERE firstName = '$deletevalue'"; //if your form enters name of the users
$deleteresult = deleteTable($deletequery);
}
function deleteTable ($deletequery)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$delete_fromTable = mysqli_query($connect, $deletequery);
print mysqli_error($connect);
}
See in your where clause WHERE name = if you are deleting on the basis of name of the user.
and also see deleteTable($deletequery); you need to pass your query not the value.
Note:
Yes, I know you are learning basic things but my recomendations are
1) Use Prepared statements, explore little bit about it
2) Delete records based on ID (unique field) not name, name (firstName) might be same for multiple users in users table
I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.
I'm trying to create multiple HTML inserts in the same form so I can quickly insert multiple lines into my database to save time. However I'm not really sure how to process this.
<form action="admin1.php" method="post">
<?php
function multiform($x){
for ($x = 0; $x < 3; $x++){
echo 'Episode: <input type="number" name="Episode[]">
Date: <input type="date" name="Date[]">
Guest: <input type="text" name="Guest[]">
Type: <input type="text" name="Type[]">
Youtube:<input type="text" name="Youtube[]"> MP3: <input type="text" name="MP3[]"> iTunes:<input type="text" name="Itunes[]"><br/><br/>';
}
}
multiform(0);
?>
<input type="submit" value="Submit Form" name="submitForm">
</form>
This is what I tried to use:
$con = mysqli_connect("server","root","","database");
function multiformpost($x) {
for ($x = 0; $x < 3; $x++) {
$Episode = $_POST['Episode'][$x];
$Date = $_POST['Date'][$x];
$Guest = $_POST['Guest'][$x];
$Type = $_POST['Type'][$x];
$Youtube = $_POST['Youtube'][$x];
$MP3 = $_POST['MP3'][$x];
$Itunes = $_POST['Itunes'][$x];
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}')";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
if (!mysqli_query($con, $sql)) {
die ('Error: ' . mysqli_error($con));
}
echo "Added to database";
}
}
multiformpost(0);
mysqli_close($con);
Which simply returns a blank screen.. I know it's wrong but I'm not entirely sure why.
You need to be building up the VALUES section of your SQL in a loop and then executing a single query. So something like this:
$con = mysqli_connect("","","","");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
multiformpost($con);
mysqli_close($con);
function multiformpost($db) {
if(empty($db) {
throw new Exception('You need to pass a valid mysqli connection to this method');
}
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ";
$size = count($_POST['Episode']);
for ($x = 0; $x < $size; $x++) {
$Episode = mysqli_real_escape_string($db,$_POST['Episode'][$x]);
$Date = mysqli_real_escape_string($db,$_POST['Date'][$x]);
$Guest = mysqli_real_escape_string($db,$_POST['Guest'][$x]);
$Type = mysqli_real_escape_string($db,$_POST['Type'][$x]);
$Youtube = mysqli_real_escape_string($db,$_POST['Youtube'][$x]);
$MP3 = mysqli_real_escape_string($db,$_POST['MP3'][$x]);
$Itunes = mysqli_real_escape_string($db,$_POST['Itunes'][$x]);
$sql .= "('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}'),";
}
$sql = rtrim($sql,',');
if (!mysqli_query($db, $sql)) {
die ('Error: ' . mysqli_error($db));
}
echo "Added to database";
}
Note that I also made the following changes which I also suggest:
I pass in DB connection to the function. I have no idea what your original parameter was being used for, since you can detect the array size of the POST arrays directly in the function. You would be even better served moving to object-oriented mysqli usage (as you could then verify an instantiate mysqli object was passed to the function), but I didn't make that change here.
I differentiated the use of $con (for global scope) and $db (for local sope in function) so that you do not confuse the two. Previously, your code referenced $con inside function scope without declaring global so that variable would not have even been available. This dependency injection approach is highly recommended as opposed to using global.
I moved DB connection error checking outside the function
I added string escaping to mitigate against SQL injection.
I moved all your global script elements together, as functions typically should not be inserted in the middle of procedural code like you have done, as that make the code more difficult to follow.
I'm trying to process a large form and hit a bit of a stumbling block. I've tried google for the answer, but I'm not quite sure I'm wording what I need right. My code looks like this.
<?PHP
$exchange = $_POST['exchange'];
$estimate = $_POST['estimate'];
$wp = $_POST['wp'];
$label1 = $_POST['name3'];
$result1 = $_POST['fb1'];
$result2 = $_POST['fb2'];
$username = "-----";
$password = "-----";
$hostname = "-----";
$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("-----", $con) or die("Could not select examples");
$query = "UPDATE btsec SET Status='$result1', TM='result2' WHERE Exchange='$exchange' AND Estimate='$estimate' AND WP='$label1' AND SectionID='$label1'";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
echo "Sections updated for WP's $wp on $estimate on the $exchange Exchange!";
mysql_close($con);
?>
What I need to do is loop through the query, but each time change the contents of the variable.
$label1 = $_POST['name3']; needs to become $label1 = $_POST['name6'];
$result1 = $_POST['fb1']; needs to become $result1 = $_POST['fb10'];
$result1 = $_POST['fb2']; needs to become $result1 = $_POST['fb11'];
As I say google isn't able to compensate for my bad wording.
The best solution would be to change the form inputs so that they work as arrays:
<input type="text" name="name[3]">
<input type="text" name="name[6]">
<input type="text" name="name[9]">
<input type="text" name="fb[1]">
<input type="text" name="fb[10]">
<input type="text" name="fb[19]">
Then when you submit the form you can iterate over the data:
foreach ($_POST['name'] as $index => $name)
{
}
foreach ($_POST['fb'] as $index => $fb)
{
}
As a side note, you also should look into using prepared statements, or at the very least escaping the data -- you're at risk of SQL injection.