Multiple criteria replace mysql record with php - php

I am collecting data from a html form, submitting the data to mysql using a php script.
However, I can't figure out how to replace/update a record if multiple criteria match.
If a new submitted record from the html form, has the same 'type', 'volume' and 'place_name' as an existing record, it should replace the 'price'.
At this moment, it is just writing a new line with the new data.
Can anyone please help me with this? Thanks!
Please see my php code below:
<?php
require("config.php");
if(!$con)
{
echo 'Not Connected To Server';
}
if(!mysqli_select_db($con,'DB3469638'))
{
echo 'Database Not Selected';
}
$type= $_POST['type'];
$volume= $_POST['volume'];
$price= $_POST['price'];
$email = $_POST['email'];
$place_name = mysqli_real_escape_string($con, $_POST['place_name']);
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$location = mysqli_real_escape_string($con, $_POST['location']);
$sql = "INSERT INTO markers (type, volume, price, place_name,
place_Location, email, place_Lat,place_Lng)
VALUES ('$type','$volume','$price','$place_name',
'$location','$email','$lat','$lng')";
if(!mysqli_query($con,$sql))
{
echo 'Not Inserted';
}
else
{
header("refresh:4; url=addprice.php");
echo "<div align='center' style ='font:40px/60px Arial,tahoma,sans-
serif;color:#ffffff'> Submitted! <br><br> Redirecting Automatically
</div>";
}
?>

First you would want to create a multi-column index in SQL on the columns you don't want to be duplicates:
CREATE INDEX multiIndex ON markers (type, volume, place_name);
Now you can use ON DUPLICATE KEY UPDATE in your PHP:
$sql = "
INSERT INTO markers
(type, volume, price, place_name, place_Location, email, place_Lat,place_Lng)
VALUES
('$type','$volume','$price','$place_name', '$location','$email','$lat','$lng')
ON DUPLICATE KEY UPDATE
price = '$price'
";

First of all, you should find out if this is a new record, or an update of an existing one. To do this, you must either incorporate IDs (recommended) or query the database first (where type, volume and place_name matches with provided one - not recommended).
Beside this, you should avoid SQL injections by not using user input directly in your SQL queries.

Related

Fetch data into table using PDO result in no value

I have a problem. I want to fetch all the tasks related to the user into a table. However, the result is '0 results'. I did try to echo print_r($allTask), and the result is Array() 1. I don't know what is the problem because, in the incomplete database, there are several tasks, but nothing shows up when I fetch it. Can someone explain it to me? Thank you for your help
Note: I put the fetch query inside the if(isset($_POST['submit']) because I want every time the user adds the new task and click submit. The incomplete database will be updated as well to display the new task added to the table
<?php
session_start();
require 'connect.php';
if (isset($_POST['submit'])) {
$owner = $_SESSION['name'];
$title=$_POST['title'];
$description=$_POST['description'];
$due_date=$_POST['due_date'];
$time=$_POST['time'];
$state=0;
$insertQuery="INSERT INTO incomplete (owner, title, description, due_date, time, state)
VALUES (:owner, :title, :description, :due_date, :time, :state)";
$preparedInsertStatement = $conn->prepare($insertQuery);
$preparedInsertStatement->bindValue(':owner', $owner);
$preparedInsertStatement->bindValue(':title', $title);
$preparedInsertStatement->bindValue(':description', $description);
$preparedInsertStatement->bindValue(':due_date', $due_date);
$preparedInsertStatement->bindValue(':time', $time);
$preparedInsertStatement->bindValue(':state', $state);
$valueInsert=$preparedInsertStatement->execute();
if($valueInsert){
echo 'Insert is done';
}
else{
echo 'Insert is not successful';
}
$displayQuery="SELECT * FROM incomplete where owner=':owner'";
$displayTask= $conn->prepare($displayQuery);
$displayTask->bindValue(':owner', $owner);
$displayTask->execute();
$allTask=$displayTask->fetchAll();
echo print_r($allTask);
if(count($allTask) > 0)
{
echo "<table border=\"1\"><tr><th>ID</th><th>Title</th><th>Description</th><th>Due
Date</th><th>Time</th></tr>";
foreach ($allTask as $row) {
echo "<tr><td>".$row["id"]."</td><td>".$row["title"]."</td><td>".$row["description"]."</td><td>".$row["due_date"]."</td><td>".$row["time"]."</td></tr>";
}
}else{
echo '0 results';
}
}
?>
When using placeholder values be absolutely sure you haven't introduced any additional syntax. I can see owner=':owner' which is incorrect. The placeholder should not have quotes around it.
This should be:
'... owner=:owner'
PDO takes care of escaping. The quotes are just in the way.

How could I prepend a field in a php form

I'm looking for a sql statement where I can add additoinal text to a form field when being submitted to a mysql database. For example: A field contains a file name that has been loaded to a Web server called "mydoc.pdf". I want to prepend the following text "http://www.example.com/uploads/", so when the form is submitted the field data becomes "http://www.example.com/uploads/mydoc.pdf".
Right now the unappended field "tofiles_link" uses the following mysql query statement to insert to the mysql database:
mysql_query("INSERT INTO site_tofiles (tofiles_title, tofiles_body,
tofiles_link, tofiles_relation, tofiles_type, tofiles_post_ip,
tofiles_post_user) VALUES
('".mysql_real_escape_string($_POST['tofiles_title'])."',
'".mysql_real_escape_string($_POST['tofiles_body'])."',
'".mysql_real_escape_string($_POST['tofiles_link'])."',
'".mysql_real_escape_string($_POST['tofiles_relation'])."',
'".mysql_real_escape_string($_POST['tofiles_type'])."',
'".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',
'".mysql_real_escape_string($_GET['tofiles_post_user'])."')");
echo "Data was Entered Successfully!\n";
mysql_close($conn);
Can this be modified to suit my puroses? THX
To make the code more readable I would do your escaping before creating the SQL query. Not required but makes the code easier to read.
$title = mysql_real_escape_string($_POST['tofiles_title']);
$body = mysql_real_escape_string($_POST['tofiles_body']);
$link = "http://www.example.com/uploads/" . mysql_real_escape_string($_POST['tofiles_link']);
$relation = mysql_real_escape_string($_POST['tofiles_relation']);
$type = mysql_real_escape_string($_POST['tofiles_type']);
$ip = $_SERVER['REMOTE_ADDR'];
$post_user = mysql_real_escape_string($_GET['tofiles_post_user']);
Notice the $link variable on the 3rd line above adds the URL to the string.
$sql = "INSERT INTO site_tofiles (tofiles_title, tofiles_body, tofiles_link, tofiles_relation, tofiles_type, tofiles_post_ip, tofiles_post_user) VALUES ";
$sql .= "('$title', '$body', '$link', '$relation', '$type', '$ip', '$post_user');";
mysql_query($sql);
echo "Data was Entered Successfully!\n";
mysql_close($conn);

Create a unique page for each project page

I'm building a simple bug tracking tool.
After you logged in you can create a new project, when you've created a new project you get redirected to the project page.
My question is, how can I give every project a unique page?
I know I only have to create 1 page (projectpage.php) and then create a unique page for each project. I have to get the id from each project.
After you fill in a form to create a new project, that form will post to this page:
project.class.php
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php');
}
else {
echo "Oops, there is something wrong. Try again later.";
}
mysql_close();
This will store the data in the MySQL database.
So, how can I make a unique page for each project?
What's the best way to do this?
Thanks in advance!
You have one PHP file, take a project id through the query string (or some other part of the URL) and query the database for the data associated with that id. Then you generate the HTML for the project page using that data.
First, mysql_* functions are obsolete, you should use PDO...
You should have a PHP script that gets a project from the database by its ID. You probably should have an ID column in your table. Here is a sample code :
if($result){
header('Location: ../project.php?id='.mysql_insert_id());
}
mysql_insert_id returns the last inserted id. See the documentation.
Then, project.php :
<?php
if (!isset($_GET['id']) || empty($_GET['id']) {
echo "error : bad url";
exit();
}
$cn = new PDO(...); // Check PDO documentation for this
$sql = "SELECT * FROM projects WHERE project_id = :id";
$stmt = $cn->prepare($sql);
$stmt->bindParam(":id", $_GET['id']);
$stmt->execute();
$project = $stmt->fetch(PDO::FETCH_OBJ);
// $project will behave like an Object, you can display for example the project name
echo $project->name;
// or the project date...
echo $project->registration_date;

PHP - Dynamic SQL Query from Dynamic POSTs

First time question, long time reader :)
I am building forms dynamically from Columns in a MYSQL DB. These columns
are created/ deleted etc.. elsewhere on my App. My form runs a query against a
SQL View and pulls in the column names and count of columns. Simple! build the form,
with the HTML inputs built with a PHP for loop, and it echos out the relevant HTML for the new form fields. All very easy so far.
Now i want a user to update these dynamically added fields and have the data added to the relevant columns - same table
as existing columns. So, as the input fields are named the same as the columns, they are posted to a PHP script for processing.
Problem is, while i have the actual field names inserted in to the SQL INSERT query, i cannot figure out how to extract the POST
data from the POST dynamically and add this to the VALUEs section of the query.
Here is my attempt....
The Query works without the variables added to it.
It works like this, first section/ is to retrieve the columns names from earlier created VIEW - as these are identical to POST names from the form. Then output to array and variable for insertion to Query. It looks like the implode function works, in that the relevant column names are correct in the statement, but i fear that my attempt to inject the column names on to the POST variables is not working.
$custq = "SELECT * FROM customProperties";
$result = $database->query($custq);
$num_rows = mysql_numrows($result);
while (list($temp) = mysql_fetch_row($result)) {
$columns[] = $temp;
}
$query = '';
foreach($columns as $key=>$value)
{
if(!empty($columns[$key]))
{
$values .= "'".'$_POST'."['".$value."'], ";
}
}
$q = "INSERT INTO nodes
(deviceName,
deviceInfo,
".implode(", ", $columns).",
nodeDateAdded,
status
)
VALUES
('" . $_POST['deviceName'] . "',
'" . $_POST['deviceInfo'] . "',
".$values."
CURDATE(),
'1'
)";
$result = $database->query($q)
Any help is much appreciated. I will feed back as much as i can. Please note, relativity new to PHP, so if i am all wrong on this, i will be glad for any tips/ advice
Regards
Stephen
If you want to get the values of every POST input without knowing the input names then you can do it this way:
//get all form inputs
foreach($_POST as $name => $value)
{
echo $name . " " . $value . "<br>";
}
If you want to get the value of certain POST inputs where you know the name of the input field then you can do it this way:
if(isset( $_GET["deviceName"]))
{
$deviceName = $_POST["deviceName"];
}
if(isset( $_GET["deviceInfo"]))
{
$deviceInfo = $_POST["deviceInfo"];
}
To connect to a database and insert the info then you have to do something like this:
$host = "localhost";
$dbuser = "username";
$pass = "password";
$datab = "databasename";
//Create DB connection
$con=mysqli_connect($host, $dbuser, $pass,$datab);
if (mysqli_connect_errno($con))
{
echo "ERROR: Failed to connect to the database: " . mysqli_connect_error();
}
else
{
echo "Connected to Database!";
}
//insert into database
mysqli_query($con, "INSERT INTO nodes (deviceName, deviceInfo) VALUES ('$deviceName', '$deviceInfo')");
(Don't forget to add mysql_real_escape_string to the $_POST lines after you get it working.)

Stopping users posting more than once

Before posting my form I am checking the database to see if there are any previous posts from the user. If there are previous posts then the script will kick back a message saying you have already posted.
The problem is that what I am trying to achieve isn't working it all goes wrong after my else statement. It is also probable that there is an sql injection vulnerability too. Can you help??4
<?php
include '../login/dbc.php';
page_protect();
$customerid = $_SESSION['user_id'];
$checkid = "SELECT customerid FROM content WHERE customerid = $customerid";
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}
else
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
To answer the second part of your question: yes, you're very vulnerable to SQL injection:
$sql="INSERT INTO content (customerid, ...) VALUES ('$_POST[customerid]', ...)";
^
This article explains SQL Injection and how to avoid the vulnerability in PHP.
You are missing curly brackets {}:
<?php
if ($checkid == $customerid) {echo 'You cannot post any more entries, you have already created one';}
else
{
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
?>
In addition to the missing curly braces mentioned previously it looks like you're assigning in the if statement, which will cause the statement to always evaluate to true:
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}
Should be:
if ($checkid == $customerid) {echo 'You cannot post any more entries, you have already created one';}
Also, $checkid contains an SQL query string. I assume you intend to actually run the query and populate $checkid with something comparable to a $customerid before actually getting to the comparison.
In addition to the SQL injections (man, read a book/tutorial about that before you start!) and the missing braces after the else, you have two errors in there: First, you don't execute the $checkid query, secondly, you only have one = in the if (so you assign the value of $customerid to $checkid.
It is also probable that there is an sql injection vulnerability too.
Why "is possible"? Don't you see that yourself? Don't you write your code in a way that you avoid such issues in the first place?
Re: sql injection - any time you trust data from your users you're vulnerable. Take your INSERT statement and sanitize it.
$sql = sprintf("INSERT INTO content (customerid, weburl, title, description) VALUES ('%d','%s','%s','%s')",
$_POST['customerid'], //forced as digit
mysql_real_escape_string($_POST['webaddress']),
mysql_real_escape_string($_POST['pagetitle']),
mysql_real_escape_string($_POST['pagedescription']) );
Also, you should use apostrophes in your array keys. In double quotes, that'd be:
echo "Post data webpage title is {$_POST['pagetitle']}";
$_SESSION will clear when the browser is closed out. Therefore, I'd suggest using Cookies for a definite way.
I've updated your code as follows:
include '../login/dbc.php';
page_protect();
$customerid = $_COOKIE['user_id'];
$checkid = "SELECT customerid FROM content WHERE customerid = $customerid";
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}else{
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
die('Error: ' . mysql_error());
else
echo "1 record added";
}
If you are worried about injection add this tidbit prior to your insert query:
foreach($_POST as $key=>$value){
$_POST[$key] = addslashes($value);
}

Categories