Is there a way to insert cookies into a database? - php

I need to match up a users name with a value inside a database, so I want to insert the users name that is saved in a cookie. The function is pretty simple. The cookie is stored correctly and I can echo it. My insert script also works cause I can insert other things. But for some reason I cannot insert a cookies value.
This is pretty much what I'm trying to do:
$username = $_COOKIE['username'];
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('error');
$query1 = "INSERT INTO Gallery (username) VALUES('$username')";
$data1 = mysqli_query ($dbc, $query1) or die('error1');
mysqli_close($dbc);
Is there something I'm missing? I tried using sessions, but no luck.
I also made the cookie accessible throughout the whole domain.

There are (at least) two problems here.
You copy the value of the cookie to a variable called $user but use a variable called $username to try to insert data into the database
You don't perform any kind of sanity check on the cookie data (which is data provided by the browser and thus tainted) before using in an SQL query. This is an invitation to Little Bobby Tables.

Possibly try changing your query to this...
$query1 = "INSERT INTO Gallery (username) VALUES(" . mysql_escape_string($_COOKIE['username']) . ")";

Related

How to use same query to insert data

I am new at programming.
I am trying to create a simple guestbok.
i have one index page where you can register a firstname, lastname and email.
And if you click on one name you redirect to a new page with id.
How can i now insert text to this ID with the same codeblock using the ID.
My code looks like this.
<?php
require('dbconfig.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=projektone", $username, $password);
//Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Insert to database
$sql = "INSERT INTO user (firstname, lastname, email)
VALUE ('".$_POST["first_name"]."','".$_POST["last_name"]."','".$_POST["email"]."')";
$sql = "INSERT INTO user (guestbok)
VALUE ('".$_POST["guestbok"]."')";
$conn->query($sql);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
header('Location: /');
?>
Thanks in advance
/Daniel
Joining up raw bits of text and passing them on to your database to process is not a good idea. It opens up your system to SQL injection. While it's unlikely that someone could compromise your site when only INSERT statements are exposed in this way, it does mean that:
anyone with an apostrophe in their name will break the logic of the request
you are exposing a method by which someone can carry out a stored XSS attack by submitting javascript to your guestbook
Regarding the SQL Injection problem, there are 2 methods to protect your system - one is to transform the data in which a way that it cannot break the SQL string it is added to (e.g. using mysqli_real_escape_string()) but the recommended approach when using PDO to mediate your code's interaction with the DBMS is to use variable binding. Here you compose your SQL command with placeholders for the data and substitute them at run time.
If your ID is generated from a mysql auto insert id, then you can read the value from $conn->lastinsertid
$stmt=$conn->prepare("INSERT INTO user (firstname, lastname, email)
VALUES (:fnm,:lnm,:eml)");
$stmt->execute(array(
':fnm' => $_POST["first_name"],
':lnm' => $_POST["last_name"],
':eml' => $_POST["email"]));
$id=$conn->lastinsertid();
Your next problem is how to communicate this securely to the page where the user submits their guestbook comment (in your example code you try to do both operations in the same page).
Sending it in a round trip to the browser, as a cookie or as form variable means that it could be tampered with. There are esoteric stateless solutions where you can do this but with the data encrypted or cryptographically signed, however the simplest solution is to use sessions - add session_start() at the top of all your pages and any data you want available across requests can be stored in the $_SESSION superglobal.
(there are security issues relating to sessions as well)
When you receive the POST containing the guestbook data, then you should use an UPDATE user SET guestbook=:gstbk WHERE id=:id_from_session (or you could INSERT it into a seperate table with id as a foreign key)
Lastly, when you output the message the person left in your guestbook, make sure you protect the browser from any nasties in there:
print htmlentities($guestbook);
Ok, probably I managed to get what you need. Put the following two lines in your dbconfig.php:
$conn = new PDO("mysql:host=$servername;dbname=projektone", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
and then require it wherever you need a database connection:
file one:
require('dbconfig.php');
$sql = "sql 1";
$conn->query($sql);
then in another file
require('dbconfig.php');
$sql = "sql 2";
$conn->query($sql);

MySQL entry storing with blank value in PHP

Have the following code that's executed when a script is ran. (I've just changed the login for display purposes).
<?php
$conn = mysql_connect("localhost", "root", "pw123");
mysql_select_db("test_db", $conn);
$sql = "INSERT INTO test_table (fname)
VALUES ('$fname')";
mysql_query($sql);
mysql_close($conn);
?>
I've edited the code down slightly so it doesn't show every value I'm trying to enter, but essentially, everything is entering as a blank value, or in the case of numerical inputs is defaulting to 0. I can't seem to figure out why this is. The variables are definitely not blank before hand as I've got them out putting on the web page to test as such.
For reference I assign $fname a value when the input box is changed using :
fname = $("#fname").val();
(Posted on behalf of OP):
Solved this myself anyway, instead of executing the MySQL statements in the initial page that user enters data, I moved it to the secondary web page, which opens once a user has submitted their information.
$fname is empty in your script and you need declarate the variable before:
$fname = 'David';
$sql = "INSERT INTO test_table (fname) VALUES ('$fname')";
:)

php mysql Insert into not working

So what I am trying to do is a very basic and straight way of inserting a record into mysql db.
It is just something I have done few times before, however for some reason it is not working with me this time.
So in the following couple of lines of code I will show my code, which basically do the following
1- Check if the user exists in the DB (An existing user is a user with the same email)
2- If the user exists in the DB then it sends an http response with a status code of 409 which means duplication.
(Anyway note that this works perfectly, which implies the connection was made successfully to the DB, and it was able to retrieve any exact user, if any)
3- If the user does not exist it should be inserted in the DB (Here is the problem)
My Code
//Checking if the user exist
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
$num_rows = mysql_num_rows($result);
if($num_rows > 0){
// Close Connection
mysql_close($con);
echo "409";
}
else{
mysql_query("INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')",$con);
// Select the record
$user_id = mysql_insert_id();
$result = mysql_query("SELECT * FROM $table_name WHERE email='".$post_email."'",$con) or die ('Error: '.mysql_error ());
// Close Connection
mysql_close($con);
echo "200 " . $result['username'];
}
I googled the possible solutions for this issue, however all similar issues I went through were because of syntax errors.
Any suggestions? Thanks in advance :)
What is the exact error message you are getting? Copy/paste that here, please.
Also, the only odd thing I see is that you are doing the SELECT commands with a variable $table_name, and in the INSERT command you are hard-coding a table name..? Maybe that's it?
INSERT INTO samam_users ...
just put the same table name variable there?
INSERT INTO $table_name ...
Let me know if this helps. :)
$sql = "INSERT INTO samam_users (username,password,email) VALUES ('ALI','AHMED','amsh-1992#hotmail.com')";
if(!mysql_query($sql,$con)) {
die(mysql_error());
}else {
echo 'inserted succesfully';
}
mysql_error() will give you information about why your query isn't working - allowing you to debug it.
Also don't use mysql_*, it's going to be deprecated and there are much better more secure options like MySQLi or preferably PDO
I think you have to put all the values in INSERT command in double quotes instead of single quote

Php MYSQL query problems

Okay so this problem is really boggeling my mind... I have a MYSQL query I want to make so that my php program can access and update the database with lat and long coordinates of a user and im getting issues...
This is non working code:
$currUsername = strtolower($_SESSION['username']);
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
The working code
$currUsername = "email_that_is_returned"
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
Is this because session returns data that is not able to be placed inside a query?
Check whether the session was started or not. if not started then add the following code to your page and then check its working or not.. i thing your session does not return any value.. so start session by using the code session_start();
session_start();
$currUsername = strtolower($_SESSION['username']);
$sql= "UPDATE users SET pos_Lat=$latitude, pos_Long=$longitude WHERE username=$currUsername";
$result = mysql_query($sql, $link);
You can check what type of data it is returning.
print $_SESSION['username'].
Also there is a chance to break the SQL query if the $_SESSION['username'] returns data with spaces. Make sure the SQL query not failing even if the $_SESSION['username'] contains spaces and singlequotes etc..

mysqli stores php variable not value

This is driving me nuts. I am using the jQuery image upload and crop from
http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop/
I am using a modified version of the suggestion on here to store the file location in a MySQL database. The mod is that I use INSERT on a table it works great except one thing, the 'owner' variable $id is being stored as $id and not as the value of $id. I can echo the value if $id on each $_POST so I know it's there.
I am pretty sure my syntax is correct but I don't understand why it is doing this.
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//connect to the database
include 'config.php';
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
$sql = "INSERT INTO `photos` (`id`,`owner`,`url`) VALUES ('id','".$id."','".$thumb_image_location."')";
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
$conn->close();}
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
The first line is 246 and the last 3 are the orginal 247-250.
Thanks for any help you can provide.
Ok, I don't know if this is my brain fart or an issue with PHP or a bit of both. I have $id assigned from the _SESSION variable in the header of each page AND (having forgotten that) I was passing $id as _POST data (same value). Once I cut out the _POST data passing and just pulled the _SESSION variable it works fine. But assigning a variable multiple times shouldn't be an issue, should it?
the query line needs to be like this:
$sql = "INSERT INTO `photos` (`id`,`owner`,`url`) VALUES ('id','$id','$thumb_image_location')";
your syntax works fine too, as seen here
this is how my syntax works, here
Note: both work the same, so still trying to figure out what's wrong in OP's code.

Categories