I've got this code with PHP PDO and I've got an INSERT query that runs twice. This code should insert the value 'Hello World' into the database. However, my code inserts the value twice into the database.
How do I fix this? I've stumbled upon other people with the same problem, but they have problems with a loop or they've used the explode function that messed something up. I don't have any of that, just one connection block and an insert query, and yet it does this weird thing.
The code:
// DB connect configuration
$user = 'user';
$pass = 'password';
// Database connection
$dsn = "mysql:host=localhost;dbname=pdotest;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$conn = new PDO($dsn, $user, $pass, $opt);
// Data to insert
$data = 'Test and test and test';
// Insert data into database
$sql = "INSERT INTO tabletwo (rowTwo) VALUES (?)";
$q = $conn->prepare($sql);
$q->execute(array($data));
It's happening because of some Javascript code for page transitions. The code can be found here: http://www.fasw.ws/faswwp/non-jquery-page-transitions-lightweight/. I have no idea how to fix this though.
Related
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.
My problem is that when I use the PDO::PARAM_LOB parameter in the bindParam() method the photo sent from the html form isn’t inserted in the MariaDB table. phpMyAdmin subsequently shows the table column ‘photo’ to be empty.
The image is successfully inserted in the table when I don’t use the PDO::PARAM_LOB but this causes a Notice: Array to string conversion in C:\xampp\htdocs\TestSite\php-sellform-handler.php on line 80 to display to the user on the web page.
There are other fields on the same form (which for simplicity I haven’t shown) which upload text and use PDO::PARAM_STR. This text data is always successfully inserted in the same table.
How do I get insert to work using PDO::PARAM_LOB?
The nearest problem to mine that I can find on S/O is PHP/PDO/MySQL: inserting into MEDIUMBLOB stores bad data
However that involves the image actually being inserted in the table, but in a corrupted form.
I’m using Apache/2.4.29 (Win32) OpenSSL/1.1.0g PHP/7.2.2 and 10.1.30-MariaDB
Here is my code:
$host = '127.0.0.1';
$db = 'test_db2';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [PDO::ATTR_ERRMODE =>PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
];
$pdo=new PDO($dsn, $user, $pass, $opt);
if (isset($_FILES ['photo'])) {
$photo=$_FILES['photo'];
$stmt_user = $pdo->prepare("INSERT INTO users_table1(photo) VALUES(:photo)");
$stmt_user->bindParam(':photo', $photo, PDO::PARAM_LOB);
$stmt_user->execute();
}
Thanks for any help!
I have used SimpleXML to get XML data from a source that required authenticiation. Using cURL I have been able to get back a result. However when I have tried to get the data into a MySQL database nothing is inserted.
Now I think it's because I have not done something to the XML data. However I am a newbie to XML data and have always worked with database stuff so could do with some help.
I have had a look around and I'm probably duplicating another question on here, but my confusion is over what I am looking at. If I can figure out the "why", I'll get to the "how"!.
Here is the output I get:
SimpleXMLElement Object
(
[bookingDataResponse] => SimpleXMLElement Object
(
[bookingDataResult] => <Bookings><SupplierCode>ABCD</SupplierCode><ServiceName>Service 1</ServiceName><UnitCode>ABC123</UnitCode></Bookings><Bookings><SupplierCode>XYZ</SupplierCode><ServiceName>Service 2</ServiceName><UnitCode>XYZ123</UnitCode></Bookings>
)
)
I presume that I need to transform the result of the above and then get that data to insert into the database. However this is where I am stuck.
I'll use PDO and a foreach to get the data into the database, but any help on getting to that point would be very useful guys.
Cheers
UPDATE # 11:18GMT:
This update covers the database insert I have coded:
$servername = "xxx.xxx.xxx.xxx";
$username = "username";
$password = "password";
$dbname = "myDatabase";
$db_cstr = "mysql:host=" . $servername . "; dbname=" . $dbname;
$conn=new PDO($db_cstr, $username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
foreach ($parser->bookingDataResponse->bookingDataResult->Bookings as $row)
{
$SupplierCode = ($row->SupplierCode);
$UnitCode = ($row->UnitCode);
$stmt = $conn->prepare("INSERT INTO `bookingData` (`SupplierCode`, 'UnitCode') VALUES (?,?)");
$stmt->execute(array($SupplierCode,$UnitCode));
}
Ive been toying with this for the last half hour and cannot figure out with the life of me what is wrong.
Ever since I've added this to my PHP document I am getting a blank page. Note, it fails on the PDO. I am not new to PDO by any means, but for some reason this failing is stumping me. All the data correlates in the database.
The page is returning blank, no errors in error log.
$value = "9EED4A5E4A54DC41195C8949C87ABA5FD6C035CD795188E179F9EF76FC7154FF";
if (!empty($_COOKIE['hash'])){
$dbuser = "user";
$dbpass = "pass";
$dbh = new PDO('mysql:host=localhost;dbname=dbname', $dbuser, $dbpass);
$stmt = $dbh->query('SELECT id FROM users WHERE hash = :hash');
$stmt->bindParam(':hash', $value);
$_SESSION['userid'] = $stmt->fetchColumn();
}
Note the cookie is being set in a previous page. The if statement works, just not the pro
query executes a query immediately. The method you want to use is prepare. You also need to call execute after the parameters are bound.
$stmt = $dbh->prepare($query);
$stmt->bindParam(":hash", $value);
$stmt->execute();
In case PDO is failing you should probably also turn error reporting on for it.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
I'm experimenting with loading a table from a file, and having difficulty. The code below is trying to take an existing database and copy it to a temporary table, then replace the original with imported data from a .csv file, and then I've got more work to do comparing the two tables before I let go of the temporary one. (Hints welcome if I should do this a different way). I get the error:
'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while
other unbuffered queries are active. Consider using
PDOStatement::fetchAll()...'
I've tried many of the suggestions from similar questions, but haven't cracked it yet. Thanks for your help! Here's my code:
<?php
//database connection
$data_source = 'mysql:host=localhost;dbname=myDB';
$db_user = 'root';
$db_password = 'pass';
$conn = new PDO($data_source, $db_user, $db_password,
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT));
if ( isset($_GET['submit']) ){
$stmt = $conn->prepare("CREATE TEMPORARY TABLE mfsw_dupe AS SELECT * FROM mfsw_test");
$stmt->execute();
$stmt = $conn->prepare("TRUNCATE mfsw_test");
$stmt->execute();
$stmt = $conn->prepare("LOAD DATA LOCAL INFILE 'C:\\xampp\htdocs\assets\mfsw_test.csv' INTO TABLE mfsw_test
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES");
$stmt->execute();
}
?>
After trying all the recommended solutions to this problem, I found that the answer was to set the PDO::ATTR_EMULATE_PREPARES option to true.
That got rid of "unbuffered queries" error, but it then started reporting a "LOAD DATA LOCAL INFILE forbidden" error on the LOAD query.
The solution to that was to set the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY option to true as well.
In short, your initial connection should look like this:
$conn = new PDO($data_source, $db_user, $db_password,
array(PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT));
I don't understand why these options are necessary, but they worked for me.
I have had exactly the same problem, tried everything mentioned above and a lot more and still couldn't avoid the "Cannot execute queries while other unbuffered queries are active" error.
However, after several hours of googling, I got it working - instead of using a prepared statement, or just query, I used 'exec' to run the 'LOAD DATA LOCAL INFILE' statement:
$stmt = $conn->exec($sql_import_csv);
I didn't need any of the aforementioned changes to the PDO options - this is my options array:
$options = array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_SSL_CA => "xxxxxxxx.crt.pem",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_LOCAL_INFILE => true
);
Hope this helps someone else out there.