I've seen so many tutorials with so many different ways to insert using PDO. None of them seem to work for me. Can't seem to get mine to send to the database. I have no issue connecting and retreiving the data using FETCH but can't seem to post this data.
Any help with getting my post to work and redirect using the header or meta refresh would be nice. I am $_POST from an html form. Connecting to the db works just fine but can't get the data in.
$hostdb = 'myremoteip';
$namedb = 'cpdemo';
$userdb = 'root';
$passdb = 'mypassword';
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
if(isset($_POST['fname'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$title = $_POST['title'];
$photo = $_POST['photo'];
$stmt = "INSERT INTO row_users (fname,lname,title,photo)
VALUES (:first,:last,:title,:photo)";
$q = $conn->prepare($stmt);
$results = $q->execute(array(
":first"=>$fname,
":last"=>$lname,
":title"=>$title,
":photo"=>$photo
));
echo 'User Added<br/>';
}
header ('Location:../insertUser.html');
exit();
What you have to understand that there is no such thing like "PDO Insert Into DB"
There is INSERT query, irrelevant to PDO but regular to database you are using.
And there is PDO prepared statement, irrelevant to query type. You have to follow exactly the same pattern, no matter if it insert or delete.
So - all you need is just a tutorial on PDO prepared statements. That's all. Preferably one that teach you to enable error reporting in the first place.
As requested by OP, comment leading to an answer (to close the question and marked as solved).
I tested your code "as is", and it worked fine.
The only thing I can tell that could be the issue is, that your insert won't happen unless it meets the conditional statement you've set if(isset($_POST['fname']))
Check to see if your HTML form's elements are indeed named?
I.e. <input type="text" name="fname"> etc. If one of those are not not named or has a typo, then your whole query will fail.
You can try binding parameter before passing it to execute, like for example in the below code
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>
Related
<?php
$host_name = '***';
$database = '***';
$user_name = '***';
$password = '***';
$link = mysqli_connect($host_name, $user_name, $password, $database);
$con = $_POST['User_ID'];
echo "Se ha ascendido al usuario $con";
$meta= 'a:1:{s:13:"administrator";b:1;}';
$consulta = 'UPDATE ***usermeta
SET
meta_value = $meta
WHERE
User_ID=$con and meta_key = "***capabilities"';
mysqli_query($link, $consulta);
echo "<br><br><br><a href='***'>Volver</a>";
In this code im trying to update an specific column from a table but it just wont work, it appears like it is working but when i go into phpmyadmin the data wont update, here is some info to keep in mind:
mysqli_connect works
query works when i execute it on phpmyadmin
i can do other queries (select) that works
data is correctly received by POST method
those " from variable $meta have to stay
I honestly dont have any idea of what is causing the code to just not work, not a single syntax error displayed or anything else. At first i thought it had something to do with the quote marks but now i dismissed that posibility.
Any help?
There's a catalog of issues here.
Your update statement is wrapped in single quotes - so your variables will not be substituted.
You've used double quotes as a delimiters for strings inside the query - that's not supported by SQL - they should be single quotes.
Table names cannot cannot contain asterisk characters.
That you are not seeing "a single syntax error" is a major issue - the DBMS will be screaming for help when it sees this.
Embedding composite data (json) in a scalar value is just asking for trouble.
Your code is vulnerable to SQL injection.
Whenever your thread of execution leaves PHP (in your code, when you call mysqli_conect() and mysqli_query()) you should be explicitly checking the result of the operation.
For one, you should have some kind of error handling so you know what the problem is. Secondly, you're calling mysqli_query directly instead of using it as a method from your already instantiated class $link.
Also, you really should be using back-ticks for column names and single quotes for column values.
Lastly, you need to escape certain special characters using mysqli_real_escape_string. Alternatively, you could use prepared statements, but I'll keep it simple. Instead of prepared statements, you can use PHP's sprintf function.
<?php
$host_name = '***';
$database = '***';
$user_name = '***';
$password = '***';
$link = mysqli_connect($host_name, $user_name, $password, $database);
$con = $_POST['User_ID'];
echo "Se ha ascendido al usuario $con";
$meta= 'a:1:{s:13:"administrator";b:1;}';
$consulta = "UPDATE `usermeta`
SET
`meta_value` = '%s'
WHERE
`User_ID`='%s' and `meta_key` = 'capabilities'";
$consulta = sprintf(
$consulta,
esc($meta),
esc($con)
);
$link->query($consulta);
echo "<br><br><br><a href='***'>Volver</a>";
function esc($v)
{
global $link;
return $link->real_escape_string($v);
}
?>
Not sure what the asterisks are in the table name, but they shouldn't be there. Also, note that I created a function for handling escaping for brevity.
EDIT:
For error handling, you should check $link->error.
Example:
<?php
$dbError = $link->error ?? null;
if (!empty($dbError))
{
die("A database error occurred: {$dbError}!");
}
?>
MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.
I'm using php and a database to add books to a database.
HTML
<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>
PHP
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');
$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";
mysqli_query($dbcon,$dbquery) or die('not queryed');
echo "Your book has been added to your online library";
I'm getting the reply ' not queryed'
try putting single quotes around the values
ie
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
You should be using PDO and prepared statements in order to prevent SQL injection. The resultant PHP would be something like this:
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Fill in these variables with the correct values ('localhost' for host, for example)
$st = $dbh->prepare("INSERT INTO books (title,author) VALUES (?,?)");
$data = array($bname, $bauthor);
$st->execute($data);
You can then add logic to check if the statement executed successfully.
Also, I think you just gave us your root password?
For more information about PDO, see this tutorial.
Check the Column names in the table,whether they match with the one in the query.also check whether they are varchar itself.
I dont find any problem in the query, and also try putting
or die(mysqli_error());
and tell what exactly you can see.
If the type is varchar , you have to use single quotes around the values.
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
OK guys, I'm having trouble with mysql_real_escape_string. It is a simple POST table with title and contents, which should in theory work fine (by me).
$db = new mysqli('...','...','...','...') or die ('error with connection');
$db->set_charset('utf8');
$title = trim($_POST['title']);
$contents = trim($_POST['contents']);
$title = mysql_real_escape_string($title);
$contents = mysql_real_escape_string($contents);
$sql = "INSERT INTO posts SET title = '$title', contents = '$contents'";
$query = $db->query($sql);
I found when I place 'echo' before and after 'mysql_escape_string' like:
echo 'before' . $title;
$title = mysql_real_escape_string($title);
echo 'after' . $title;
that it echoes the title on the "before" line, but on the "after" line it echoes blank $title.
Note: whan I use 'mysql_escape_string' instead (of real), it works fine (but I guess this is weaker protection).
Any ideas??
Thank you.
The reason title is empty is because mysql_real_escape_string is returning FALSE.
This happened because it requires a MySQL connection to the database, you have MySQLi. From the docs,
A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned
The way to fix the issue is to use mysqli_real_escape_string to match your database connection, as suggested in the other answers. Obviously for security, you're better off using prepared statements.
Also, the database link needs to be supplied. Since you're using the OO style, this is done as
$db = new mysqli()
$title = $db->real_escape_string($title)
mysql_real_escape_string() works in context of connection made by "mysql" extension, but you use "mysqli".
You need to either connect using mysql_connect() not recommended
Or you need to use new approaches from mysqli such as prepared statements or mysqli_real_escape_string()
You should not interpolate user-generated strings into sql. Use prepared statements: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
In your case:
$db = new mysqli('...','...','...','...') or die ('error with connection');
$db->set_charset('utf8');
$title = trim($_POST['title']);
$contents = trim($_POST['contents']);
$sql = $db->prepare("INSERT INTO posts (title, contents) VALUES (?,?)");
$sql->bind_param('ss', $title, $contents);
$sql->execute();
is this code ok? because I don't get my db updated and I get no errors. Thank you.
//connect to db
$email = $mysqli->real_escape_string($_POST['email']);
$bo = $mysqli->real_escape_string($_POST['bo']);
$p1 = $mysqli->real_escape_string($_POST['p1']);
$p2 = $mysqli->real_escape_string($_POST['p2']);
$dt = $mysqli->real_escape_string($_POST['dt']);
$dt = new DateTime("2012-07-01 13:13:13", new DateTimeZone('Europe/Paris'));
//more validation code...
$stmt = $mysqli->prepare('UPDATE table SET Password=?, R_P=?, R_T=? WHERE E_mail=?')
$stmt->bind_param("ssss", $p2, $p2, $dt, $email);
$stmt->execute();
$stmt->close();
$mysqli->close();
//send email
I had no errors because I forgot to add on my page a thing that I always add on all my pages:
// check for errors
require_once('check_all_errors.php');
You encode the data twice, one manually and once by supplying them to a prepared statement. Just encode it once, like:
$stmt = $mysqli->prepare('UPDATE table SET Password=?');
$stmt->bind_param('s', $_POST['password']);
By the way, unless you truly want to write MySQL-specific code, there's no reason to use mysqli anymore. The PDO module supports multiple databases out of the box, with a similar interface.