mysqli->prepare('Update') - php

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.

Related

MySQL not using PHP variables properly in Queries, replacing the variables with strings/integers works fine

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.

PHP and MySQL mysqli->prepare keeps failing in FPDF file

Ok. I'm trying to prevent SQL injections on my first project build with FPDF.
(Since my insecure solution is working I suspect it has nothing in particular to do with FPDF. Just thought I'd mention that this is used to get data for generating a PDF :) )
The code below is working mighty fine. But it vulnerable to injections:
$mysqli = mysqli_connect('','','',''); // Empty on purpose due to posting here :)
$IDQuery = mysqli_query($mysqli,"SELECT ID FROM sendsubmits WHERE ID = $ID");
The $ID is an integer taken from the url like this:
$ID = htmlspecialchars($_GET["ID"]);
As far as I understand I need to swap $ID with ?. And then use bind_param to have it inserted.
I've tried and follow the doc here:
http://php.net/manual/en/mysqli-stmt.bind-param.php
And my result is this:
$mysqli = new mysqli('','','',''); // Empty on purpose due to posting here :)
/* Check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$IDQuery = $mysqli->prepare('SELECT ID FROM sendsubmits WHERE ID = ?');
$IDQuery = bind_param('i', $ID);
$IDQuery = execute();
printf('%d Row inserted.\n', $stmt->affected_rows);
$IDQuery->close();
This isn't working. And I can't seem to figure out why.
Any suggestions?
Not $IDQuery = bind_param('i', $ID);
but $IDQuery->bind_param('i', $ID);
The same with execute. Next time try to understand what you read in manual

PHP MySQLInsert prepared statements

I am working on learning about PHP prepared statements and implementing them when using the MySQL INSERT command. I am able to do this just fine without the prepared statements, but I am confused on where I went wrong in my code after adding prepared statements.
The below code gives me the "Internal Server Error", but it appears to be syntactically correct.
EDIT:
Here is dbConnet.php:
<?php
$hostname = "*";
$username = "*";
$database = "*";
$password = "*";
$link = mysqli_connect($hostname, $username, $password, $database);
if (!$link)
{
die('Could not connect: ' . mysqli_connect_error());
}
?>
Code:
<?php
include('dbConnect.php');
$stmt = $mysqli->prepare("INSERT INTO Articles (content, date) VALUES (?,?)");
$stmt->bind_param('si', $article, $submitTime);
$article = $_POST['articleArea'];
$submitTime = new DateTime();
$submitTimeString = $submitTime->format("m-d-Y H:i:s");
$stmt->execute();
if (mysqli_query($link,$stmt) )
{
echo "<script language='javascript'>alert('Article has been submitted!')</script>";
echo "<script language='javascript'>window.location = 'URL'</script>";
}
else
{
echo "<script language='javascript'>alert('Uh oh! An error has been encountered! Please try to resubmit your article.')</script>";
echo "<script language='javascript'>window.location = 'URL'</script>";
}
mysqli_close($link);
?>
Any insight into my issue is greatly appreciated. If you need me to add more info, please let me know!
Thanks in advance
Try using
$stmt = $link->prepare("INSERT INTO Articles (content, date) VALUES (?,?)");
$stmt->bind_param('ss', $article, $submitTimeString);
$article = $_POST['articleArea'];
$submitTime = new DateTime();
$submitTimeString = $submitTime->format("m-d-Y H:i:s");
Instead of
$stmt = $mysqli->prepare("INSERT INTO Articles (content, date) VALUES (?,?)");
$stmt->bind_param('si', $article, $submitTime);
$article = $_POST['articleArea'];
$submitTime = new DateTime();
$submitTimeString = $submitTime->format("m-d-Y H:i:s");
If that error is being caused by trying to connect to the database with both $link and $mysqli (as pointed out by deceze) this should fix that issue. As for the date, I would suggest changing "date" to a "text" datatype in your database (hence the $stmt->bind_param('ss', $article, $submitTimeString); vs $stmt->bind_param('si', $article, $submitTimeString);)
Your database connection is $link, yet you use $mysqli->prepare(..). Which is it?
You're execute()ing the $stmt, yet you also next use mysqli_query(). That's nonsense. Use one or the other, not both.
mysqli_query() expects a query string, but you're giving it a prepared statement object.
You're binding $submitTime to the statement, which is a DateTime object, which mysqli will likely not like. You're never using your formatted date $submitTimeString anywhere.
Any one of these mistakes will likely trigger the fatal error. You need to rewrite that from scratch. Read the manual for how to use the mysqli extension.
is $submitTime defined at the time it is bound to $stmt?
Both $article and $submitTime are initialized after being bound.
And you should bind the date string, not the DateTime object.
the $submitTimeString format is wrong. MySQL expects datetimes as date('Y-m-d H:i:s') (year first)

Variant characters in PDO statement doesn't work in IE9

I'm using PHP 5.4.31 and MySQL version 5.5.39-MariaDB. My database is in utf8_general_ci collation and some of my fields contain latin variants like á and é.
I am using the mysql:charset=utf8 directly in my PDO statement which works fine in Chrome and FireFox (on PC, Mac and tablet). But doesn't work in IE9.
If I use a URL such as "url_of_page.php?firstName=Joe&lastName=González" IE9 cannot find the record.
// get variables from URL
$fName = $_GET["firstName"] ;
$lName = $_GET["lastName"] ;
try {
$dbh = new PDO("mysql:charset=utf8;host=$hostname;dbname=databaseName", $username, $password);
/*** set the error reporting attribute ***/
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** The SQL SELECT statement ***/
$stmt = $dbh->prepare("SELECT * FROM Table WHERE FirstName = :firstName AND LastName = :lastName");
/*** bind the paramaters ***/
$stmt->bindParam(':firstName', $fName, PDO::PARAM_STR);
$stmt->bindParam(':lastName', $lName, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$stmt->execute();
/*** fetch the results ***/
$result = $stmt->fetchAll();
foreach($result as $row) {
I've also tried using $stmt->execute("set names utf8"); which makes no difference. Don't understand why this is a browser issue. Any idea why IE is having problems?
The problem was that I had not used urlencode when assigning my URL variables and my URL was not in a valid ASCII format. After using urlencode my correct URL was something like:
url_of_page.php?firstName=Joe&lastName=Gonz%C3%A1lez
instead of
url_of_page.php?firstName=Joe&lastName=González

PDO Insert Into DB

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

Categories