Get Users Comment From Mysql using Php - php

I'm trying to allow a user to comment on a profile on my website. I have the following php -- updated:
<?php
// Insert Comments into Database that user provides
$comm = mysql_real_escape_string($_POST['addComment']);
$pID4 = filter_input(INPUT_GET, 'pID', FILTER_SANITIZE_NUMBER_INT);
$cID = mysql_real_escape_string($_POST['courseInfoDD']);
$username = "###";
$password = "####";
$pdo4 = new PDO('mysql:host=localhost;dbname=###', $username, $password);
$pdo4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth3 = $pdo3->prepare('
INSERT INTO Comment (info, pID, cID)
VALUES(:info, :pID, :cID)
');
$sth3->execute(array(
':info' => $comm, ':pID' => $pID3, ':cID' => $cID
));
?>
DB Table "Comment"
http://postimage.org/image/16sbr0jd0/ (Moderator please convert this to show image, please)
HTML:
<input type='text' id='addComment' name='addComment' tabindex='3' value='Enter comment' />
Error Given:
No pID specified . When I try to insert a comment.

You are using single-quotes in your insert statement :
$sth3 = $pdo3->prepare('
INSERT INTO Comment (info, pID, cID)
VALUES($comm, $pID3, $cID)
');
With those simple quotes, $comm will not be evaluated -- and the literal $comm string will be sent to the database -- resulting in something you probably don't quite expect.
If you want variables to be interpolated, you should use double-quotes around your string.
But, as you are trying to use prepared statements, that's not what you should do, actually.
Instead, you should use placeholders in the statement -- and, then, bind those to your data, when executing the statement.
Your prepare would look a bit like this, I suppose :
$sth3 = $pdo3->prepare('
INSERT INTO Comment (info, pID, cID)
VALUES(:comm, :pID3, :cID)
');
Note the :comm, :pID3, and :cID placeholders.
And, then, when executing the statement, you'll actually pass some real data, to correspond to the placeholders :
$sth3->execute(array(
':comm' => $comm,
':pID3' => $pID3,
':cID' => $cID,
));
Additional note : as you are using prepared statements, you don't have to use mysql_real_escape_string() (which is not a PDO-related function, BTW, and should only be used when working with mysql_* functions) : the escaping is dealt by the prepared statement mecanism itself.

The parameters to the PDO prepared statement should be used like this:
$sth3 = $pdo3->prepare('
INSERT INTO Comment (info, pID, cID)
VALUES(:info, :pID, :cID)
');
$sth3->execute(array(
':info' => $comm, ':pID' => $pID3, ':cID' => $cID
));
First set up the "slots" for the values, then supply them when you run the query.

$variables in single quote strings are not being processed. Use double quotes instead and add quotes for the SQL statement itself:
$sth3 = $pdo3->prepare("
INSERT INTO Comment (info, pID, cID)
VALUES('$comm', '$pID3', '$cID')
");

our problem has nothing to do not with mysql not with comments.
It's basic PHP strings syntax.
Use double quotes if you want variables to be interpreted in a string.
However, you shouldn't add variables into query directly, but rather bins them

Related

PDO dont work when trying to execute INSERT command

i'm trying to INSERT a sql query but it does not work - I got no errors, $pdo->errorInfo(); only returns Array and in the mysql is nothing to see!
Im 100% sure that $text, $file and $title is set (i've check that with echo) In every other php file this pdo connection works with include but not in the dev.php what should i do???
datenbank.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'password');
?>
dev.php
include("datenbank.php");
// Prepare an insert statement
$post = $pdo->prepare("INSERT INTO news (text, date, file, title) VALUES ($text, NOW(), $file, $title)");
$post->execute();
$help = $pdo->errorInfo();
You don't use the parameters markers in your prepare PDO stament. When you prepare a query using PDO extension, you need put markers in your query statement and indicate the value of those markers in the execute function like an associative array.
You can use markers like :marker or question marks ? and your query would be like that:
include("datenbank.php");
// Prepare an insert statement with marks params
$post = $pdo->prepare(INSERT INTO news (text, date, file, title) VALUES (:text, NOW(), :file, :title));
//execute statements with the marks values in prapare function params
$post->execute(array(':text' => $text, ':file' => $file, ':title' => $title));
Edit: PD: This prevents the SQL inyection.......
for string value you need quote
$post = $pdo->prepare("INSERT INTO news (text, date, file, title)
VALUES ('$text', NOW(),'$file', '$title')");
anyway you should not use php var in sql , you are at risk for sqlinjection .. use prepared statements and binding param instead
$stmt = $conn->prepare("INSERT INTO news (text, date, file, title)
VALUES (:text, NOW(), :file, :title)");
$stmt->bindParam(':text', $text);
$stmt->bindParam(':file', $file);
$stmt->bindParam(':title', $title);
$stmt->execute();

PHP Prevent SQL Injection

I'm trying to prevent SQL Injection using PHP with PDO. I've used this as a reference. http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers . My code doesn't give me any error but the values that are getting in are all null.
The vlaues I'm trying to insert are not null. I know this because I've echo'ed them out:
echo "\nDate: ".$date." Name: ".$name." mail: ".$mail."Comment: ".$comment." website: ".$website;
$sql = "INSERT post SET timeDate = :timeDate and name = :name and mail = :mail and comment = :comment and website = :website";
$stmt = $db->prepare($sql);
$stmt->bindParam(":timeDate", $date);
$stmt->bindParam(":name", $name);
$stmt->bindParam(":mail", $mail);
$stmt->bindParam(":comment", $comment);
$stmt->bindParam(":website", $website);
$stmt->execute();
Don't use AND in between your assignments—use commas.
$sql = "INSERT post
SET timeDate = :timeDate,
name = :name,
mail = :mail,
comment = :comment,
website = :website";
Your statement using AND between the terms is no error, because the statement is actually valid. It just doesn't do what you thought it would.
It's as if you did this:
SET timeDate = (:timeDate and name = :name and mail = :mail and comment = :comment and website = :website")
This sets only timeDate to the result of one long boolean expression.
The other columns are not getting assigned anything, they're just being compared to parameterized values. Since this is a new row you haven't inserted yet, all the other columns are naturally NULL, so the comparisons will be NULL. Therefore AND-ing them together will be NULL, and that's the ultimate value that will be assigned to your timeDate column.
The other columns are not assigned any value in this statement, and their default is presumably NULL.
This is a weird and useless statement, but strictly speaking, it's not an error.
I also encourage you to use PDO more simply. Instead of using bindParam() for everything, you can pass an array to execute(). This does the same thing as if you had done bindValue() for each of the parameters. You can do this with named parameters or positional parameters.
$stmt = $db->prepare($sql);
$stmt->execute([
"timeDate" => $date,
"name" => $name,
"mail" => $mail,
"comment" => $comment,
"website" => $website]);
This is especially handy if you already have your parameter values stored in an array.
The protection against SQL injection is just as good as using bindParam().

Inserting a variable with a comma in it to SQL database?

I've been trying to insert a variable that has a comma in it to a SQL database for 30 minutes or so. I've echoed the variable, and the comma is there, but when it inserts, there's no comma!
Example (some code like mine):
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO table (`column`) VALUES ('$variable2')";
$query1 = mysqli_query($con,$sql1); //I dont think I need to put a con variable up there for an example code
And when I do:
echo $variable2;
The result is test, with the comma, but the data in the column is just test WITH NO COMMA.
Help please.
Thanks.
Edit:
Your Common Sense fixed it, apparently I needed brackets around '$variable2' so it's like:
$sql1 = "INSERT INTO table (`column`) VALUES (('$variable2'))";
Thanks Your Common Sense and everyone else who tried!
Well, the answer is simple.
It's your own code does remove this comma, either before insert or after fetch.
If you care to write a reproduceable test case, you will see that noone is taking your comma.
Test case means code that involves the behavior in question and nothing else. Not a single line of code beside insert and fetch:
$variable1 = "test";
$variable2 = "$variable1,";
$sql1 = "INSERT INTO users (username) VALUES ('$variable2')";
mysqli_query($db,$sql1);
$sql2 = "SELECT username FROM users WHERE username ='$variable2'";
$res = mysqli_query($db,$sql2);
$row = mysqli_fetch_row($res);
var_dump($variable1, $variable2, $sql1, $sql2, $row[0]);
run it, see it all with comma in place, and then search your own code for the comma trimming code
or may be you have just test without comma in your table, ans select this one all the time, instead of one with comma.
or whatever silly error of the like
Try it like this:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO table ('column') VALUES (?)");
$stmt->bind_param($variable2);
/* execute prepared statement */
$stmt->execute();
This is more safe and will not trigger such strangeties. (Is that a word?)
What happens here is, that the query is send to the sql database and this returns a statement. The statement has some holes, these are the ?, in it.
When using bind_param you fill the holes and then you can execute.
This has a couple of advantages:
It is safe
You can reuse your statement
It is easier than string interpolation stuff
Try "INSERT INTO table ('column') VALUES ('" . $variable2 . "');"

MYSQLI prepared statement bind_param types does not work

I have been using prepared insert statements for some years and assumed it was binding parameters properly or would give an error but it seems not as the following php binds and inserts a record without any errors but changes a string which should be an int to a zero. So it may be ok for preventing SQL injection attacks but you would end up with a spurious record in the table. e.g.:
$q = "INSERT INTO `table` (id1, id2) VALUES (?, ?)";
$stmt = mysqli_stmt_init($dbc);
$stmt->prepare($q);
$id1 = 'aaaaaaa';
$id2= 'aaaaaaa';
$result = $stmt->bind_param('ii', $id1, $id2);
echo '<p>' . $result . '</p>'; // Trying to bind a string to an int returns true!
echo $dbc->error; // nothing
$stmt->execute(); // inserts record changing $id2 to zero but auto-increments primary key $id1
echo $dbc->error; // nothing
This is running in an Xampp environment with Apache/2.2.14, PHP/5.3.1 and MySQL 5.1.41. Can anyone tell me what is going on?
$stmt->bind_param() doesn't check the given variables for a certain type, it only converts them into the specified type. And your string 'aaaaaaa' is converted into an int-value: 0. That's the way php does it.
The database insert statement is the wrong place to check, if your variables contain useful/correct values. Do that before and only try to insert them, if your validations work.
To do the validation for an int, you could use the php-function is_numeric() or is_int().
I'm not an expert for sure, but at first look.
You have:
$id1 = 'aaaaaaa';
$id2= 'aaaaaaa';
$result = $stmt->bind_param('ii', $id1, $id2);
Thing is your 'ii' parameter says that you will be binding integers! And in fact your $id1 and $id2 are strings. For strings you should go with:
$result = $stmt->bind_param('ss', $id1, $id2);

mysql escaping single and double quotes

I have a script that i am writing to move certain fields to a new db like
$results = mysql_query ( "SELECT body, title FROM $source_db.Post" );
while ($row = mysql_fetch_array($results)) {
if(mysql_num_rows($users_result) > 0){
$insert = "INSERT INTO wp_posts (`body`,`title`) VALUES ('{$row['body']}', '{$row['row']}')";
mysql_query($insert);
}
}
but as you can see the query will break everytime due to the single and double quotes, is there a solution to this problem like herdok or something
INSERT INTO wp_posts (`body`,`title`)
VALUES
('Here are the final returns from today's ...<br /><br />he stayed home...<br />
<div class="entry-content">
<div class="entry-body">', 'something')
mysql_real_escape_string is made for just this.
PHP: mysql_real_escape_string
$insert = "INSERT INTO wp_posts ('body','title') VALUES ('".mysql_real_escape_string($row['body'])."', '".mysql_real_escape_string($row['row'])."')";
The other option is to use mysqli and prepared statements
$stmt = $this->db->prepare("insert into table (id,name,longstring) values (?,?,?));
$stmt->bind_param('iss',$row["id"],$row["name"],$row["body"]);
$stmt->execute();
mysqli will bind the assigned parameters to the ? in the prepared statement as an integer (i) or a string (s).
The sanest approach is to use bound parameters. Bobby Tables has examples.

Categories