insert click_url, timestamp and username when user clicks a link - php

i was going to have a menu consisting of images which differed depending on if a new record was added since the users last visit.
However I decided to move away from that idea and I am now going for comparing last timestamp on clicked link with timestamp on new record.
I tried to find a solution but I am stuck at this line right now, maybe you can see what's wrong with it (clicks is my table where I want to store the clicks):
$sql = "insert into clicks (username, link_url, click_timestamp) values ($_SESSION[$username], "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", now())";
$result=mysql_query($sql);
So, anybody have any good ideas? :)

You have an error in your SQL syntax, try this:
$sql = 'INSERT INTO clicks (username, link_url, click_timestamp) VALUES
("' . $_SESSION[$username] . '",
"http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '",
NOW()
)';

Check that string. As ar as I know, PHP can solve plain variables inside a string, but cannot solve an array, so $_SESSION in this case should go outside the string. Also, if you want to put quotes inside a string, use a backslash before it, like \", so it's gonna be interpreted as a quote character instead of an end of string.

Related

saving information to database from webform

$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW())";
$query = "INSERT INTO address ". "(house_number,street_name,town/city,postcode,province/county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county', NOW())";
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
So I can create a connection to my database no problem and on my previous page I can send username and password to the database but then I come to the user details page to save the information and continually getting Invalid query 2 error. The table names are correct (users & address) and all variables are spelt correctly. Does anyone have a suggestion to fix the issue or a better alternative (I mean to just point me in the right direction of the research I should be looking at if I am way off target, if I have just mispelled something or have something in the wrong place then I would appreciate the heads up, have been at this quite a while now)
This is the code from the previous page and it works fine and sends the information to the database:
$query = "INSERT INTO login ". "(username,password) ". "VALUES('$uname','$epass', NOW())";// sets up sql query
$result = mysqli_query($conn, $query) or die("Invalid query 2"); // runs query using open connection
mysqli_close($conn); // close database connection
As far as I know all the database side of things is fine, all data types are varchar except for dob which is date (I have tried changing this to varchar to see if it fixed the problem but it didnt) and userID is int and is an autoincrement for the unique primary key. I have also tested the php file without the validation rules and still gives the same error.
Quite a few things wrong here.
First you are reassigning the variable $query; so the first insert will be getting overwritten by the second, you need to concat the variable.
Then you have 2 queries you are attempting to send at one time. However you never tell Sql you've finished your first before starting your second.
Try the following instead take note Of The semi colons ; at the end of each.
You are also putting slashes into your column names which is illegal.
Lastly, you've got more values to insert than you have columns. Remove the now() from the end.
$query = "INSERT INTO users ". "(first_name,last_name,dob,mobile_number,landline_number,email) ". "VALUES('$fname','$sname','$dob','$mobile','$landline','$email');";
$query .= "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county');";
Although this will now work, I highly recommend you do some research regarding safe practices with Sql.
Here would be a great starting point https://www.w3schools.com/php/php_mysql_prepared_statements.asp
On a side note, why are you concating your Strings? There's no need
$query = "INSERT INTO users (first_name,last_name,dob,mobile_number,landline_number,email) VALUES('$fname','$sname','$dob','$mobile','$landline','$email', NOW());";
Maybe it's the fact that you are closing the connection after your first call.
try or die(mysqli_error($conn));
EDIT:
Delete passing value "NOW()".
code:
$query = "INSERT INTO address ". "(house_number,street_name,town_city,postcode,province_county) ". "VALUES('$hnumber','$addr','$town','$pcode','$county')";

Issue with MySQL INSERT via PHP mysql_query

I'm having problems with a really bizarre problem when trying to insert a record into mysql via PHP and I was wondering if anyone could shed any light on it, because I'm out of ideas now.
Database table:
Field Type Null Default Comments
UserID bigint(20) No Autoincrement
UserGUID text No
ServerID int(11) No
UserName text No
Passwrd text No
Prompt text No
Answer text No
EMail text No
Verified int(11) No 0
Language text No
Gender int(1) Yes NULL
DateOfBirth int(11) Yes NULL
Country int(11) Yes NULL
PostCode text Yes NULL
State text Yes NULL
Town text Yes NULL
Snippit of relevant PHP code...
public function signupUser($uid, $pwd, $prompt, $answer, $email, $lang, ... &$result)
{
$guid = $this->getGUID();
$serverID = 1;
$result = mysql_query("INSERT INTO User(UserGUID, ServerID, UserName, Passwrd, EMail) " +
"VALUES ('$guid', $serverID, '$uid', '$pwd', '$email')");
Before anyone tells me I should be using mysqli, parameterising my queries and the like, please be aware that this PHP/MySQL is a local test harness only, on a private network and only for development purposes until the real web service (dotNet/Oracle) comes available.
So if I call the function above with suitable parameters, $result comes back with...
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0' at line 1"
but if I reduce the query to just...
$result = mysql_query("INSERT INTO User(UserGUID, ServerID, UserName, Passwrd) " +
"VALUES ('$guid', $serverID, '$uid', '$pwd')");
it works! Happily inserts the record (despite there being nulls in not null fields!?!) Just to add further complications, if I run the (original) query with suitable values e.g.
INSERT INTO User(UserGUID, ServerID, UserName, Passwrd, EMail) VALUES ('guid', serverID, 'uid', 'pwd', 'email')
directly against the database via phpMyAdmin, it also works!!
This is driving me nuts. I've tried changing field names, nullability, order, which fields I use in the query (after the first four which work), values - none of it makes a difference. It almost seems as if it doesn't want more than four fields.
Please... anyone...? I really am at a loss to understand why it won't accept the fifth field, it makes no sense that I can see. Unfortunately the error returned is of no help at all, too vague and seems to be the equivalent of the oh-so-useful "errors occurred" from MS.
If I have to change over to mysqli I will but I'd prefer not to have to re-craft the test harness if I can avoid it.
edited after a revelation: take a look in the comments that concatenation operator in php is absolutely a . not a + i would put money that is your problem right there... didnt even see it on my first look.
in the past ive run into odd troubles somewhat similar to this - and was able to solve it by encapsulating my table and column names in backticks columnX, columnY - i would also try adding a space between the table name 'User' and the parenthesis containing your column names in the SQL syntax
mysql_query("INSERT INTO User(UserGUID, ServerID, UserName, Passwrd, EMail) " +
"VALUES ('$guid', $serverID, '$uid', '$pwd', '$email')");
take a look at this question? very similar to yours with successful results
hope i could be of some assistance
If your example is literal, I doubt either works. The string concatenation operator is "." not "+" in php. Additionally, php will not interpret variables inside single quotes. Try re-writing the query like this:
$result = mysql_query("INSERT INTO User SET UserGUID = '" . $guid . "', ServerID = " . $serverID . ", UserName = '" . $uid . "', Passwrd = '" . $pwd . "'";
I always create SQL inside a string, and, if there is a problem, I insert an echo $sql or error_log($sql) statement.
Sometimes there's something very subtle. When you copy and paste the query from debug output into phpMyAdmin, you will see a more meaningful error message.
One thing is possible that the variable $email contains something that breaks out of the string. Make sure you use mysql_real_escape_string on your PBP variables before including them inside an SQL query..

mysql error with insert command

So , am creating a password change table
When some 1 changes pass , i insert his username, newpass and the confirmation code in PassChange table, (so i send him a confirmation e-mail after) the idea is simple and here's the code i use
$insertResult=mysql_query("INSERT INTO TempChangePass (UserName, NewPass, ConfirmationCode) VALUES ('$UserName', '$newPass', '$code')") or die (mysql_error());
though i get this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'username'', '4da59df8d4007807e7230e0881fbf774', '16585482')' at line 1
NOTE: All the columns format in the table is set to varchar.
The connection to mysql database is fine, the table name is currect.
This problem is driving me crazy , i just can't figure out where the problem is, if anyone here can help me will be very thankful :)
and thanks in advance.
EDIT:
I actually got it solved, and just for people who visit this post by searching for solutions, if you got similar problem with your sql command, try echo it, and see how exactly the string is moved to the database :-) , happy coding everyone.
And sorry if I wasted any of your time :) am just very new to php & mysql :D
Remove the single quotes around your variables. PHP is interpreting them as strings.
$insertResult=mysql_query("INSERT INTO TempChangePass (UserName, NewPass, ConfirmationCode) VALUES ('" . $UserName. "', '" . $newPass. "', '" . $code . "')") or die (mysql_error());
Additionally, you might want to do something like this:
$sql = "INSERT INTO TempChangePass (UserName, NewPass, ConfirmationCode) VALUES ('" . $UserName. "', '" . $newPass. "', '" . $code . "')";
echo $sql;
Take that echo, and try to manually run it.
Looks something like sql inyection. I'm quite sure your $username is $username = "username'". Look at the single quote. So the query became:
$insertResult=mysql_query("INSERT INTO TempChangePass (UserName, NewPass, ConfirmationCode) VALUES ('username*''*, '4da59df8d4007807e7230e0881fbf774', '16585482')") or die (mysql_error());
Did you try to do the Query one column by one ?
i mean :
INSERT INTO TempChangePass (UserName) values ( '$UserName' );
then add it up ?
Works for me mostly when I get errors ;)
Just an idea.
It looks like you have single quotes in your actual username -- you're actually passing in 'username' instead of just username. Try removing those, see if it will work after that.
The recommended way to deal with this issue (and prevent SQL injection) is to use prepared statements, however if you really want to, you could probably do this inline using mysql_real_escape_string($UserName) (reference)
Try this:
$insertResult=mysql_query("INSERT INTO TempChangePass(UserName, NewPass, ConfirmationCode) VALUES('$UserName', '$newPass', '$code')") or die (mysql_error());
You have some extra spaces in your SQL.
try using a sanitizing script before you make the query.
use
mysql_real_escape_string()
EDIT
You should now use the MySQLi version
mysqli_real_escape_string()
or OOP method
mysqli::real_escape_string()
Why use MySQLi instead of MySQL?

my sql query doesn't insert anything, what am i doing wrong?

i'm trying to insert a query into a database, however for some reason it's not working, perhaps you guys can see something i don't.
i know the enrties is right (as the checking bit does work on another page and so does the db selection.
it's starting to drive me nuts by now, and so is my project mate.
the query is used in PHP, after having filled a form. (on a different page).
$insert_query = "INSERT INTO enrties(
datum,
naam Relatie,
ContactPersoon,
bezoekreden)
VALUES (
'$_SESSION[Datum]',
'$_SESSION[RelatieNaam]',
'$_SESSION[ContractPersoon]',
'$_SESSION[redenBezoek]')";
mysql_query($insert_query);
my thanks in advance.
p.s: i'm using php my admin
EDIT: none of them did the trick, but i solved it because there was a , to much somewhere else >.<
naam Relatie is not a valid field name. Field names must be a single word, or escaped to "hide" the space. Beyond that, fieldnames with spaces in the name are bad practice, and as you can see, are VERY prone to causing just such problems.
$insert_query = "
INSERT INTO enrties
(`datum`,`naam Relatie`,`ContactPersoon`,`bezoekreden`)
VALUES ('$_SESSION[Datum]','$_SESSION[RelatieNaam]','$_SESSION[ContractPersoon]','$_SESSION[redenBezoek]')";
mysql_query($insert_query);
You should wrap field names in ` , and strings in '
mysql_error() will probably point you in the right direction as others have said.
Another point to note is that you shouldn't have array elements directly in your strings without enclosing them in curly braces, and field names with spaces in them should be enclosed in backticks.
My best guess for why it is failing though is that you have spelled the table name wrong. It should probably be "entries".
I would try this:
$insert_query = "INSERT INTO `entries` (`datum`,
`naam Relatie`,
`ContactPersoon`,
`bezoekreden`)
VALUES (
'{$_SESSION['Datum']}',
'{$_SESSION['RelatieNaam']}',
'{$_SESSION['ContractPersoon']}',
'{$_SESSION['redenBezoek']}')";
mysql_query($insert_query) or die(mysql_error());
you cannot have a field name with space so change naam Relatie to naam_Relatie that might can help you

Seeking assistance with Escaping Data for MySQL queries

Please don't send me a link to php.net referencing mysql_real_escape_string as the only response. I have read through the page and while I understand the general concepts, I am having some trouble based on how my INSERT statement is currently built.
Today, I am using the following:
$sql = "INSERT INTO tablename VALUES ('',
'$_SESSION['Member1FirstName'],
'$_SESSION['Member1LastName'],
'$_SESSION['Member1ID'],
'$_SESSION['Member2FirstName'],
'$_SESSION['Member2LastName'],
'$_SESSION['Member2ID'] ....)
and the list goes on for 20+ members with some other values entered. It seems most people in the examples already have all their data stored in an array.
On my site, I accept form inputs, action="" is set to self, php validation takes place and if validation passes, data is stored into SESSION variables on page 2 then redirected to the next page in the process (page 3) (approximately 8-10 pages in the whole process).
You seem to already know that you should be using mysql_real_escape_string but I guess you don't know how to use. You need to apply it for each user supplied string you insert into your SQL. The following example should clarify this:
$sql = "INSERT INTO tablename VALUES ('', '" .
mysql_real_escape_string($_SESSION['Member1FirstName']) . "', '" .
mysql_real_escape_string($_SESSION['Member1LastName']) . "', '" .
etc..
Or alternatively look into prepared statements and bind parameters for an easier (and faster) solution.
1) you're missing your closing single-quote and vars aren't replaced inside of single quotes.
2) mysql_real_escape_string is the answer, but try it with sprintf:
$sql = sprintf("INSERT INTO tablename VALUES ('', '%s', '%s', '%d' )",
mysql_real_escape_string( $_SESSION['Member1FirstName']),
mysql_real_escape_string( $_SESSION['Member1LastName']),
$_SESSION['Member1ID']); // %d forced it as a digit
http://us2.php.net/manual/en/function.sprintf.php
Why can't you use mysql_real_escape_string?
You can also use a regexp to only allow certain characters that would be expected in a name

Categories