Not inserting data to database from link - php

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

Related

php variables in sql statements for login

I am fairly inexperienced with php and sql and I am having an issue with php variables in the insert into SQL statement.
I have a SQL Table :
CREATE TABLE users (
userID INT PRIMARY KEY,
username VARCHAR(256),
password VARCHAR(256)
);
This isn't the way I made the table as it was made in phpmyadmin but that is exactly how it is
the PHP is so , there is validation code aswell but it is not necessary:
$userUsername = $_POST["username"];
$userPassword = $_POST["password"];
$sqlinsert = "INSERT INTO users(username,password) VALUES ('$userUsername','$userPassword');";
$insertquery = mysqli_query($conn,$sqlinsert)
or die ("Problem with insert query");
Either you need to assign auto increment to primary key (userID).
Or you have to pass value for it like
$sqlinsert = "INSERT INTO users(userID, username, password) VALUES (1, '$userUsername', '$userPassword');";
if you have Auto Increment in ID then leave a blank first
$sqlinsert = "INSERT INTO users(userID,username,password)
VALUES ('','$userUsername','$userPassword')";
Or fill it with ID if not Auto Increment.
$sqlinsert = "INSERT INTO users(userID,username,password)
VALUES ('1','$userUsername','$userPassword')";
And as already mentioned in comments of your post your code is vulnerable to SQL Injection.
can use PDO Prepare Statement,too not necessarily ofcourse

SQL INSERT fails even if the new row is in the DB?

I'm using mysqli in a PHP class.
I have this query to be executed:
INSERT INTO notifications (userid, content, uniq, link) VALUES (48, "[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9c602a02a26114a625", "http://website/somepost")
It fails, showing the error:
You have an error in your query etc. to use near '"[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9"'
But if I look in the DB, the new row is present.
The parameters are escaped using mysqli_real_escape_string():
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ($userid, \"$msg\", \"$uniqid\", \"$link\")";
// die($sql);
$this->query($sql);
I tried to check query execution with $mysqli->affected_rows and !$result of mysqli_query().
The fields types are
INT (11) for userid,
TEXT for content,
TINYTEXT for uniq and
TINYTEXT for link.
All of the TEXT fields have collation "utf8_general_ci".
I didn't create the table.
The strange thing is that if I look in the database, the query was successfully executed...
Why is this happening?
you sql should be like
$userid = $this->escape($userid);
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$link = $this->escape($link);
$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ('$userid', '$msg', '$uniqid', '$link')";

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']."')";

MySQL Insert from PHP

I'm having a little trouble with my insert statement this morning. Yes, I am using the deprecated mysql_query function. My insert statement looks as follows:
$query3 = "INSERT INTO ".$db_prefix ." offer_det
(fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
VALUES '".$fname."', '".$lname."', '".$_10k."', '".$_14k."',
'".$_18k."', '".$_21k."', '".$_22k."', '".$_24k."',
'".$_925."', '".$coins."', '".$bars."')";
$result3 = mysql_query($query3);
My PHP form values are all the variables listed in the first part of the insert statement, 'fname', etc.
My variables are set to pull from the post and are listed as the values going into the insert.
I had to change the variables to underscore before they started, I guess PHP didn't like that.
My questions:
Are those 10k, 14k, etc, okay mysql table row names?
Is there an issue I'm missing here?
The datatype for fname and lname are varchar and for the 10k through bars are decimal (7,3).
The column name 925 must be quoted using backticks.
(`fname`, `lname`, `10k`, `14k`, `18k`, `21k`, `22k`, `24k`, `925`, `coins`, `bars`)
You may also want to consider changing the column names to something else to avoid further similar problems in the future.
You should quote the 925 column name, as per MySQL Schema Object names
So correctly:
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, `925`, coins, bars)
values
('".$fname."', '".$lname."', '".$_10k."', '".$_14k."', '".$_18k."', '".$_21k."',
'".$_22k."','".$_24k."', '".$_925."', '".$coins."', '".$bars."')";
Another recommendation: you should escape the incoming strings, because SQL injection is a nasty thing to experience...
Use the QUERY as like follow..
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
values ('$fname', '$lname', '$_10k', '$_14k', '$_18k', '$_21k', '$_22k',
'$_24k', '$_925', '$coins', '$bars')";
$query_exec=mysql_query($query3) or die(mysql_error());
And for inserting a variable you need to use single codes only..
Can I be bold and suggest a change in your implementation?
/// put your vars in an easier to use format
$insert = array(
'fname' => $fname,
'lname' => $lname,
'10k' => $_10k,
/* and so on ...*/
);
/// considering you are using mysql_query, use it's escape function
foreach ( $insert as $field => $value ) {
$insert[$field] = mysql_real_escape_string($value);
}
/// pull out the keys as fields and the values as values
$keys = array_keys($insert);
$vals = array_values($insert);
/// the following should auto backtick everything... however it should be
/// noted all the values will be treated like strings as you were doing anyway
$query = "INSERT INTO `" . $db_prefix . "offer_det` " .
"(`" . implode('`,`', $keys) . "`) " .
"VALUES ('" . implode("','", $vals ) . "')";

INSERT PHP Statement not working

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

Categories