Stopping users posting more than once - php

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);
}

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.

Multiple criteria replace mysql record with 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.

How to POST a newly defined variable into SQL - beginners PHP

The sql column avatar_link isn't updating:
A form submits data and directs to the script (partial) below. The SQL columns: name, comment, email and story_id all insert fine. The image saves to the server with no problem (I didn't include that part of the script to keep things brief). $templink is a newly created variable that should represent the URL of a image uploaded. I'm redefining the variable as $avatar_link and using POST.
$tempLink = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
$page_path = $_POST['page_path'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $_POST['email'];
$storyid = $_POST['storyid'];
$avatar_link = $_POST['$tempLink'];
$con=mysqli_connect
("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'INSERT INTO comments (name, comment, email, storyid, avatar_link, entry_date)';
$sql .= 'VALUES("'.$name.'", "'.$comment.'", "'.$email.'", "'.$storyid.'", "'.$avatar_link.'", now())';
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
I marked the title of this 'beginners PHP' because this question seems very basic (and I can't still figure it out)...if that is not appropriate let me know and I will remove.
$_POST variables come from a submitted form. If you are simply defining a variable and passing it into a statement for insertion into a database, you could eliminate a few steps here, and just do this:
$avatar_link = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
Also, pay attention to #Marc B's comment here. You can learn about parameterizing mysqli statement all over the web, or here on Stack Overflow. What's really best, and what I'd recommend, is learning PDO.

inserting data in mysql previously defined variables

I am using this code to get data from Json and insert them to mysql. However it inserts no records in the data base.
<?php
include("db.php");
$currsiteurl = 'http://graph.facebook.com/1597233119';
$graph = json_decode(file_get_contents($currsiteurl));
$id = $graph->id;
echo "id : ".$id;
echo "<br>";
$username = $graph->username;
echo "username : ".$username;
echo "<br>";
$gender = $graph->gender;
echo "gender : ".$gender;
echo "<br>";
$locale = $graph->locale;
echo "locale : ".$locale;
mysql_query("INSERT INTO users_data (id, username, gender, locale)
VALUES ('.$id', '.$username', '.$gender', '.$locale')");
?>
Can any one show me whereis the mistake ?
mysql_query("INSERT INTO users_data (id, username, gender, locale)
VALUES ('.$id', '.$username', '.$gender', '.$locale')");
You are creating a single string (with embedded variables) so the dots '.' are not required.
If either of the id or gender are number-fields then this is likely to be what prevents the data from being inserted (with the dots). (If they are numbers they don't require surrounding apostrophes either.)
In addition to what Andy G states:
You should use prepared statements to make sure the data you are receiving is properly escaped to avoid sql injection attacks: http://php.net/manual/en/pdo.prepared-statements.php
To assist debugging queries, add echo mysql_error() after your mysql_query statement to print the error (or use one of the new fangled methods mentioned in the alert here: http://us1.php.net/manual/en/function.mysql-error.php)

Why can't I INSERT INTO?

So this might be dumb, but I can't get anything to insert into a MySQL on a certain account, and I've been staring at this for two hours. I'm a newbie to PHP, so I could very well be doing something dumb. I attached a screen shot of the DB I am trying to INSERT INTO.
Here is what I'm talking about:
(imgur seems to be down for me)
Here's the code I have, and PhpMyAdmin told me GRANT ALL PRIVILEGES ON . TO ...
$fbFirstName = $me['first_name'];
$fbLastName = $me['last_name'];
$fbEmail = $me['email'];
mysql_real_escape_string($fbFirstName,$fbLastName,$fbEmail);
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID=$uid");
$userrowsreturned=mysql_num_rows($getuserresult);
if ($userrowsreturned=0)
{
echo '<br />user already exists, will update something here eventually<br />';
}
else {
$sql = mysql_query("INSERT INTO newusers (fbUID,callsAttempted,callsMade,fbEmail,fbFirstName,fbLastName) VALUES ($uid,'1','0',$fbEmail,$fbFirstName,$fbLastName)");
if(!$sql) {
die("Nope");
} else {
echo "1 record added";
}
echo '<br />created user<br />';
}
Two things go wrong here. Escaping goes like:
$fbFirstName = mysql_real_escape_string($fbFirstName);
// for all variables
// or, just in one go:
$fbFirstName = mysql_real_escape_string($me['first_name']);
// and for integers, make sure they are actually integers (and prevent mayhem)
$some_id = (int)$me['some_id'];
$uid = (int)$uid;
And when inserting you must quote non-integer values:
$sql = mysql_query("INSERT INTO `newusers`
(`fbUID`,`callsAttempted`,`callsMade`,`fbEmail`,`fbFirstName`,`fbLastName`)
VALUES
('$uid',1,0,'$fbEmail','$fbFirstName',$fbLastName')");
(but you may quote integers as well - you never know if some external id is, or may become, alphanumeric.)
You have an error
if ($userrowsreturned=0)
should be (use double equals to test equivalence, single equals for assignment)
if ($userrowsreturned==0)
I also think you actually mean the following since you're checking if a user already exists
if ($userrowsreturned==1)
first of all you must change
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID=$uid");
to
$getuserresult = mysql_query("SELECT * FROM newusers WHERE fbUID='$uid'");
after that change your insert to:
$sql = mysql_query("INSERT INTO newusers (fbUID,callsAttempted,callsMade,fbEmail,fbFirstName,fbLastName) VALUES
('$uid','1','0','$fbEmail','$fbFirstName',$fbLastName')");

Categories