INSERT PHP Statement not working - php

So, I'm not exactly sure what the problem is, but, when I try to INSERT into a table, it doesn't work.
All the variables are working. I've echoed and tested them, they are working.
$username = $_SESSION['username'];
$update = $_GET['update'];
mysql_query("INSERT INTO updates (username, update) VALUES ('$username', '$update')");
So it must be a problem with my mySQL query. This mySQL query is one of two in the .php folder. If that makes any difference.

Error in SQL
There is an error in your SQL. You cannot use MySQL keywords in column names without quoting them.
In this case update needs to be enclosed in backticks:
$query = "INSERT INTO updates (`username`, `update`)
VALUES ('$username', '$update')";
SQL injection
Your code is susceptible to SQL injection attacks. You should escape quoted strings that are placed into an SQL statement with mysql_real_escape_string() or bind your data using PHP PDO prepared statements.
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
Putting it together
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
$query = "INSERT INTO updates (`username`, `update`)
VALUES ('$username', '$update')";
I have written little SQLFiddle for you so you can see this in action: http://sqlfiddle.com/#!2/c25b1/1

You need to escape the data you are about to insert. You also want to separate the string from the variables.
Try something like this:
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
mysql_query("INSERT INTO `updates` (username, update) VALUES ('" . $username . "', '" . $update . "')") or die(mysql_error());
That's untested but should work.

mysql_error() is the best way but you can also echo your query and run it directly against the database to see what is the problem.
$username = $_SESSION['username'];
$update = $_GET['update'];
$query = "INSERT INTO updates (username, update) VALUES ('$username', '$update')";
mysql_query($query);
echo "My Query : $query";

try this:
$username = $_SESSION['username'];
$update = $_GET['update'];
mysql_query("INSERT INTO updates (username, update) VALUES ('+$username', '+$update')");
also is better is create a variable to put the query string and then you make the query

Related

pg_query INSERT INTO not working

I have a setup With Apache24, php environment and postgresql database.
I'm trying to populate some columns (not all) in db table with values, but it is not working as I would expect.
I get the following error/warning and db is not populated:
Warning: pg_query(): Query failed: ERROR: syntax error at or near "c329a92850f6d539dd376f4816ee2764517da5e0235514af433164480d7a" LINE 1: ...word, salt) VALUES (DEFAULT, cff#jjj.no, per, 8254c329a92850... ^ in C:\Users\Public\Server\Apache24\htdocs\eMe\newuser.php on line 34
Any support on this is highly appreciated. I have searched for similar questions but not been able to interpret the answers into my context.
<?php
# Registration form input to postgresql user table in myDB
session_start();
# Retrieve data from input form
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
# Concatenate and hash password with salt
require_once(dirname(__DIR__).'\eMe\saltgenerator.php');
global $randString;
#$randString = pg_escape_string($randString);
$isalt = pg_escape_string($randString);
$saltandpassword = $isalt. $password;
$hashedpassword = hash('sha256', $saltandpassword, false);
$username = pg_escape_string($username);
$email = pg_escape_string($email);
$hashedpassword= pg_escape_string($hashedpassword);
# Insert data into Postgresql database
# INSERT INTO table_name (column1, column2, column3 .....) VALUES (value1, value2, value3....)
include_once(dirname(__DIR__).'\eMe\config.php');
$query = "INSERT INTO users (userid, mailaddress, username, userpassword, salt) VALUES (DEFAULT, $email, $username, $hashedpassword, $isalt)";
#$result =
#pg_query_params($query);
pg_query($query);
?>
I have tried to include quotes and backtick quotes as described on this link but it does not solve the problem. The error/warning is slightly different though:
Warning: pg_query(): Query failed: ERROR: syntax error at or near "`" LINE 1: INSERT INTO users (userid, `mailaddress`, `username`, `use... ^ in C:\Users\Public\Server\Apache24\htdocs\eMe\newuser.php on line 30
The only problem in your code is you didn't figure out yet that when writing that:
$username = pg_escape_string($username);
$username gets escaped for injection, which is good, but this will add necessary quotes inside the value, not around the value (see Whats does pg_escape_string exactly do? for more).
So in the query, quotes are needed around the literal text values in addition to escaping the contents, as in the following:
$query = "INSERT INTO users (userid, mailaddress, username, userpassword, salt)
VALUES (DEFAULT, '$email', '$username', '$hashedpassword', '$isalt')";
(given that the variables in this query have already been passed through pg_escape_string)

php script not connecting to MySQL database

I have a php "verifyconect.php" script which has my connection to the server. When I fill out my form page it is meant to write the data to the MySQL database but it does not do this. I have also changed the hostname to "localhost" although this is being hosted on the web. I inputted the server hostname which works with my FTP software but no change occurs. Please what am I getting wrong.
verifyconect.php
<?php
$link = mysql_connect ("hostname", "###", "###");
mysql_select_db ("dbtable", $link);
?>
VerifyLogin.php
<?php
include("verifyconect.php");
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
$insert = 'INSERT INTO verifytable (username, email, password, confirm_password) VALUES ("'.$username.'", "'.$email.'", "'.$password.'", "'.$confirm_password.'")';
mysql_query($insert);
?>
You are switching up the single and double quotes.
Suppose
username = john
email = john#example.com
password = hell0w0rld
confirm = hell0w0rld
then the query will be this:
INSERT INTO verifytable (username, email, password, confirm_password) VALUES ("john", "john#example.com", "hell0world", "hell0w0rld")
Using double quotes in SQL queries give a syntax error. To use literal values in SQL queries, you must use single quotes.
So if you rewrite the line with your $insert variable to the following:
$insert = "INSERT INTO verifytable (`username`, `email`, `password`, `confirm_password`) VALUES ('".$username."', '".$email."', '".$password."', '".$confirm_password."')";
you will be good.
Also note that I surrounded the SQL table column names with backticks, so if you use a keyword (like password) as column name, it won't give syntax errors.
Update
It seems that in some cases using double quotes for (literal) values to insert into a SQL table, sometimes will work too. However, according to this answer, you better stick to single quotes.

inserting data from a form into your mysql database using php

i used this code
<?php
$conn = new PDO("mysql:host=localhost;dbname=CU4726629",'CU4726629','CU4726629');
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
header('Location: reviews.php');
?>
but it keeps giving me this error
Parse error: syntax error, unexpected T_VARIABLE in
/home/4726629/public_html/check_login.php on line 5
Take this for an example:
<?php
// insert some data using a prepared statement
$stmt = $dbh->prepare("insert into test (name, value) values (:name, :value)");
// bind php variables to the named placeholders in the query
// they are both strings that will not be more than 64 chars long
$stmt->bindParam(':name', $name, PDO_PARAM_STR, 64);
$stmt->bindParam(':value', $value, PDO_PARAM_STR, 64);
// insert a record
$name = 'Foo';
$value = 'Bar';
$stmt->execute();
// and another
$name = 'Fu';
$value = 'Ba';
$stmt->execute();
// more if you like, but we're done
$stmt = null;
?>
You just wrote a string in your above code:
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ("$_POST['username']","$_POST['moviename']","$_POST['ratings']")";
Above answers are correct, you will need to concat the strings to form a valid sql query. you can echo your $sql variable to check what is to be executed and if is valid sql query or not. you might want to look in to escaping variables you will be using in your sql queries else your app will be vulnerable to sql injections attacks.
look in to
http://php.net/manual/en/pdo.quote.php
http://www.php.net/manual/en/pdo.prepare.php
Also you will need to query you prepared sql statement.
look in to http://www.php.net/manual/en/pdo.query.php
A couple of errors:
1) you have to concat the strings!
like this:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
2) you are not using the PDO at all:
after you create the "insert" string you must query the db itself, something like using
$conn->query($sql);
nb: it is pseudocode
3) the main problem is that this approach is wrong.
constructing the queries in this way lead to many security problems.
Eg: what if I put "moviename" as "; drop table review;" ??? It will destroy your db.
So my advice is to use prepared statement:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (?,?,?)";
$q = $conn->prepare($sql);
$fill_array = array($_POST['username'], $_POST['moviename'], $_POST['ratings']);
$q->execute($fill_array);
You forgot dots:
$sql="INSERT INTO review (username, movie_name, ratings)
VALUES (".$_POST['username'].",".$_POST['moviename'].",".$_POST['ratings'].")";
and fot the future for now your variables are not escaped so code is not secure
String in a SQL-Statment need ', only integer or float don't need this.
$sql="INSERT INTO review (username, movie_name, ratings) VALUES ('".$_POST['username']."','".$_POST['moviename']."','".$_POST['ratings']."')";

Not inserting data to database from link

So when someone press this link, it should insert all the data from that text id to a new table but with the username who clicked it and the id of the text the user pressed.
The problem is, when a user clicks the link, it doesn't insert the data, what could be wrong?
The session works, so it must be something with the GET?
<?php
if(isset($_GET['collect'])) {
$perman = $_GET['collect'];
$username = $_SESSION['username'];
$query = $dbh->query("INSERT INTO collections (id, ad, user) VALUES ('', $perman, $username)");
echo 'Saving';
echo $perman;
header ('Refresh: 1; URL=http://localhost/de/collect.php');
}
?>
First, inserting '' for ID isn't very good (don't know if it works), don't use it (uses default), or insert NULL (uses default too, if NOT NULL).
Second, to insert values it's good practice to enquote it and use escape_string on it. I think that's your problem.
$query = $dbh->query("INSERT INTO collections (ad, user) VALUES ('" . $dbh->escape_string($perman) . "', '" . $dbh->escape_string($username) . "')");
You should be doing it like this...if you're using PDO
Much safer, with prepared statements
$sql = "INSERT INTO books (id,ad,user) VALUES (:id,:ad,:user)";
$q = $conn->prepare($sql);
$q->execute(array(':id'=>null,':ad'=>$perman,':user'=>$username));
You tagged your Question with "PDO". Are you using PDO? If yes, why are you not using bindParam() or bindValue()?
If $perman and $username are strings, you've to escape them:
$query = $dbh->query("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES ('', '{$perman}', '{$username}')");
That query should work, but there are still security issues. You've to escape the values. With PDO it's very simple.
General: use http://php.net/manual/en/function.mysql-error.php
Your column "id" should be Integer and have an auto_increment. Of course some IDs are Strings, but if you're able to avoid it, avoid it!
You could print out the $_GET params by using
print_r($_GET);
Edit
Example with PDOStatement::bindValue():
$stmt = $dbh->prepare("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES (:id, :ad, :user)");
$stmt->bindValue(":id", 123);
$stmt->bindValue(":ad", "ad");
$stmt->bindValue(":user", "username");
$stmt->execute();

Update SQL tables through php form

Query is running however not being sent to SQL server.
My Current Register Script.
$link = mysqli_connect("$server", "$user", "$pass", "$webdb");
$username = mysqli_real_escape_string($link, (string) $_POST['username']);
$displayname = mysqli_real_escape_string($link, (string) $_POST['display_name']);
$email = mysqli_real_escape_string($link, (string) $_POST['email']);
$password = sha1((string) $_POST['password']);
$query="INSERT INTO user (`username`, `nicename`, `email`, `password`)
VALUES ('$username', '$displayname', '$email', '$password', '1')";
mysqli_query($link, $query);
mysqli_close($link);
echo $query;
?>
The output I recieve from the Query:
INSERT INTO user (username, nicename, email, password) VALUES ('orion5814', 'Orion5814', 'my#abc.com', '72f2ac484bee398758e769530dd56228d905884d', '1')
I've checked all my link variables and they're all set correctly as far as having the right information in place, so I don't know where else to go from here. Sorry for all the questions; you can view it at doxramos.org if you think it would help at all.
The query is flawed. You name 4 columns (username, nicename, email, password), but you list 5 values ('orion5814','Orion5814','my#abc.com','72f2ac484bee398758e769530dd56228d905884d','1')
If you remove the last value, the query should work.
Also, you could simplify your code by using the object oriented interface to mysqli like this:
$username = $link->real_escape_string($_POST['username']);
and
$link->query($query);
$link->close();
You also don't need to explicitly cast the variables as strings since that is done automatically if needed for your code.
As jordi12100 suggested it is good pratice that you check errors while you connecting to database or executing queries.
You can do it like this:
$link = mysqli_connect("$server", "$user", "$pass", "$webdb") or die( "Error:" . mysqli_connect_error());
mysqli_query($link, $query) or die ("Error:" . mysqli_error($link));
This can give you idea what you did wrong.
Hope this helps.
Probarly an error in your query.
Catch the error with mysqli_error();

Categories