I am a bit lost with my prepared statement. My goal it to read a simple small csv file (100 lines and about 10 columns) into a mysql database.
Since I couldn't get that to work I simplified the mysql table to one column for now (OrderUuid). The first part of the code I hardcoded a testvalue for my OrderUuid variable, which gets added to mysql fine. However, when I take the column value form the csv file (line[0]), nothing (an empty string I think) gets added to the db table.
Here is my code:
while(($line = fgetcsv($csvFile)) !== FALSE){
//This works!
$OrderUuid = "Test";
$insertQry2 = $conn->prepare("INSERT INTO orders_test (OrderUuid) VALUES (?)");
$insertQry2->bind_param("s", $OrderUuid);
if(!$insertQry2->execute()){trigger_error("there was an error....".$conn->error, E_USER_WARNING);}
//This doesn't
$OrderUuid = $line[0];
echo $OrderUuid."<br>"; //Returns something like: d17e91d5-63b9-4a56-a413-3274057073c7
$insertQry3 = $conn->prepare("INSERT INTO orders_test (OrderUuid) VALUES (?)");
$insertQry3->bind_param("s", $OrderUuid);
if(!$insertQry3->execute()){trigger_error("there was an error....".$conn->error, E_USER_WARNING);}
}
Any help would be appreciated!
Thanks!
Norm
EDIT 1:
Thanks for all the tips guys! I rewrote the code, but unfortunately the script is still inserting empty strings into my table. There is no error messages whatsoever.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$flag = true;
$data = array();
while(($line = fgetcsv($csvFile)) !== FALSE){
if($flag) { $flag = false; continue; }
$data[] = $line;
}
if (!($stmt = $conn->prepare("INSERT INTO orders_test (OrderUuid) VALUES (?)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->bind_param("s", $data[0][0])) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
foreach($data as $dat) {
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
}
Here is my super simple table:
CREATE TABLE orders_test (
OrderUuid varchar(500) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
For anyone that is interested, it was actually super simple in the end. The file contained some letters that the database interpreted as lots of line breaks I think. Therefore applying
strip_tags
did the trick.
Related
I have currently a problem on streaming results from a mysql table. This table has more than 10,000,000 rows. And the structure
ID, IndexField1, Data1
With Primaryindex on ID and Index on IndexField1.
In PHP I tied to stream parts of the data (about 7 Mio) to calculate and verify some parts. For this reason I hava a callback which is been called for every single response.
public function streamForIndexedColumn(int $columnId, callable $callback){
$stmt = NULL;
$sql = "SELECT id, indexedField, data1 FROm myTable WHERE indexedField1 = ?;";
if (! ($stmt = $this->mysqlConn->prepare ( $sql ))) {
throw new Exception("ERROR");
}
try {
if (! $stmt->bind_param ( "i", $columnId)) {
throw new Exception( "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error );
}
$item = new Item ();
if (!$stmt->bind_result($item->id,$item->indexfield1,$item->data1)) {
throw new Exception( "Binding output parameters failed: (" . $stmt->errno . ") " . $stmt->error );
}
if (! $stmt->execute ()) {
throw new Exception("Execute failed: (" . $stmt->errno . ") " . $stmt->error );
}
$cnt = 0;
while ( $row = $stmt->fetch() ) {
$cnt++;
$callback($cnt, $item);
}
if ($row ===FALSE){
throw new Exception("MySQL Error: (" . $stmt->errno . ") " . $stmt->error );
} finally{
$stmt->close ();
}
}
This runs sometimes for several hours. Sometimes it is running, sometimes it is failing with message "MySQL Error: (0) "
Are I am getting the error reason in a wrong way? Are there any configurable Limits on the server or client which may produce this error?
I am using Mysql 5.17.19 and PHP 7.0.29.
The exception in $row === FALSE will always be thrown because after it fetches all rows, $row will be false.
$stmt->errno will return 0 because (Quoted from the docs: http://php.net/manual/en/mysqli.errno.php)
Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.
I found out earlier today that I am quite behind with using prepared statements. I tried to make a prepared statement to get some data out from my database.
I would like to print all the rows in my database, but I am not quite sure how to do that in my while loop?
<?php
/* Prepare */
if ($stmt = $mysqli->prepare("SELECT * FROM stores")) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Bind and execute */
$id = null;
$headline = null;
$description = null;
$place = null;
if (!$stmt->bind_param("i", $id, "s", $headline, "s", $description, "s", $place)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
while ($stmt->fetch()) {
/* Loop through my rows in MySQL and print all rows*/
echo $id, $headline, $description,$place;
}
/* Close Statement */
$stmt->close();
/* Close Connection */
$mysqli->close();
?>
if (!$stmt->bind_param("isss", $id, $headline, $description, $place))
{
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
You'll want to do that. As #Fred-ii said in the comments. You've got the syntax wrong.
How it works is that the first parameter of bind_param is all your data types as one string, then you list your data afterwards. Ensure that you use the right data type and the right amount of parameters.
Update
Having inspected your code further, I realise you haven't use prepare correctly. I'll include a demonstration below so you can use it as a guide.
$stmt = $mysqli->prepare("SELECT * FROM myTable WHERE id = ? AND name = ?");
if (!$stmt->bind_param("is", $id, $name))
{
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute())
{
echo "Execution failed: (" . $stmt->errno . ") " . $stmt->error;
}
The question marks delineate each variable. This means that you put a ? where you want a variable to go.
Then you use bind_param to list your data types (as stated above) with your variables or data following.
Update 2
$errors = array(); // store errors here
$stmt = $mysqli->prepare("SELECT name FROM myTable WHERE id = ?"); // prepare our statement
// check that our parameters match, if not then add error
if (!$stmt->bind_param("i", $id))
{
array_push($errors, "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error);
}
// if no errors and statement fails to run
if (count($errors) <= 0 && !$stmt->execute())
{
array_push($errors, "Execution failed: (" . $stmt->errno . ") " . $stmt->error);
}
// no statement errors
if (count($errors) <= 0)
{
$stmt->bind_result($name); // store the results of the statement in this variable
// iterate through each row of the database
while ($stmt->fetch())
{
echo $name;
}
}
// report the errors
else
{
echo "<h3>Errors</h3>";
foreach ($errors as $error)
{
echo "<p>$error</p>";
}
}
$errors = array()
Here I create an array that will hold all of our error messages.
array_push($errors, "...")
The array_push function will add a variable to the array in the syntax of array_push($array, $var) where $array is the array that will have items added, and $var is the item you want to add.
I use this so that I can add errors in a neat way, that can be later iterated.
count($errors)
The count function will count the number of elements in an array.
I use this to see if any errors have been added to the array. When I initialise $errors there are no elements in it so it will return 0.
$stmt->bind_result($name)
This is written outside of the while loop since it is used to tell the statement that we want to store all of the column name inside this variable named $name.
while ($stmt->fetch())
This will iterate through each row in the database. Each iteration of the while loop will be one row of the database. In my example, I simply echoed the value for the name column.
It is possible to store more than one column. Just add the column in the SQL query (SELECT col1, col2, col3 FROM mytable) and then store each column in a variable in bind_result ($stmt->bind_result($col1, $col2, $col3);. Note that they do not have to be the same name as the column; this is also valid $stmt->bind_result($myVar, $someVar, $anotherVar);).
foreach ($errors as $error)
foreach takes an array and iterates through it, storing each iteration in the variable following as.
In this instance we have errors stored in an array named $errors, and we store each one in $error and write it in a paragraph tag.
my problem is that I want to loop through an array and insert every entry of that array into another column of an mySQL table. To be honest, I'm not sure if that's the best way to design my database, but that's one way I could imagine, it works. If someone has a better idea of how to do it or a link for best practice or something, that would be awesome.
So what I want to do: I have a form where someone can register to offer a food delivery service. He can enter name etc. and up to 10 offers (limitation of the database table). These information should be insert into the table 'anbieter' into the fields 'angebot_0' , 'angebot_1' ...
So what I did is:
if (isset($_POST['register_offer']) and isset($_POST['anbieter-email'])){
$name = $loc = $cat = $email = $password ="";
$angebot = array();
// fill all variables
$name = test_sql($_POST['anbieter-name']);
$email = test_sql($_POST['anbieter-email']);
$password = test_sql($_POST['anbieter-password']);
$loc = test_sql($_POST['anbieter-loc']);
$cat = test_sql($_POST['anbieter-cat']);
// fill $angebot with all given angebot[] entries
foreach($_POST['angebot'] as $ang) {
$angebot[] = test_sql($ang);
}
if(!empty($name) and !empty($loc) and !empty($email) ){
/* decrypt password */
$password = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);
// insert name, email, password, location and category into database
/* Prepared statement, stage 1: prepare */
if (!($stmt = $conn->prepare("INSERT INTO anbieter (anbieter_name, anbieter_email, anbieter_password, anbieter_loc, anbieter_cat) VALUES (?, ?, ?, ?, ?)"))) {
echo "Prepare failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param('sssss', $name, $email, $password, $loc, $cat)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$userid = $stmt->insert_id;
// safe all angebot[] entries to database - angebot[0]-> angebot_0
for($x=0; $x < count($angebot) ; $x++) {
$upd = $conn->prepare("UPDATE anbieter SET angebot_".$x." = ? WHERE abieter_ID = ? ");
$upd->bind_param('si', $angebot[$x], $userid);
$upd->execute();
}
So when I do this, I get the error:
Fatal error: Call to a member function bind_param() on boolean in ...
It's a super bad way to do that by using $x to name different fields of the table, but that's the only way I could think of it works :/
I hope someone can help me here! :)
Thanks a lot!
My suggestion instead on single record update query multiple times you can do it in a single query,
Eg:
$query = "UPDATE anbieter SET";
for ($x = 0; $x < count($angebot); $x++) {
$query .= " angebot_" . $x . " = '" . $angebot[$x] . "', ";
}
echo $query .= " WHERE abieter_ID = " . $userid;
So thanks for you help, but it didn't help much :/
After trying some other possibilties, I solved it like:
$x = 0;
foreach($angebot as $offer){
if (!($upd = $conn->prepare("UPDATE anbieter SET angebot_".$x." = '". $offer. "' WHERE anbieter_ID = " . $userid))) {
echo "Prepare failed: (" . $upd->errno . ") " . $upd->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$upd->execute()) {
echo "Execute failed: (" . $upd->errno . ") " . $upd->error;
}
$x = $x+1;
}
Maybe it will help someone else :)
I have read everything I can think of to get an explanation but nothing seems to help. If someone might be able to point out the obvious or give me a slight idea of what is wrong. I have read through php.net and the mysqli tag and can't seem to figure this out. Everything I read says you can't send two queries but I am only trying one. Any help would be much appreciated.
This->https://stackoverflow.com/a/9649149/1626329 - States that maybe I have multiple result sets but I am not sure that makes much sense or what I can do to get more detail on the inner workings of prepared statements.
My Code:
class mydb {
public function __construct() {
// Connect to Database
$this->mydb = new mysqli('****', '***', '***', '***');
if ($this->mydb->connect_errno) { // Error on connection failure
echo "Failed to connect to MySQL in Construct: (" . $this->mydb->connect_errno . ") " . $this->mydb->connect_error;
}
}
public function choose ($select, $from, $config = 0, $options = NULL) {
if ($config === 0) { /** Configure statement for prepare depending on options */
$stmt = 'SELECT ' . $select . ' FROM ' . $from;
} elseif ($config === 1) {
$stmt = 'SELECT ' . $select . ' FROM ' . $from . ' WHERE ' . $options['where_comp'] . ' LIKE ?';
} elseif ($config === 2) {
$stmt = 'SELECT ' . $select . ' FROM ' . $from . ' WHERE ' . $options['where_comp'] . ' = ?';
} /** End if/elseif Prepare statemenet */
$mydb = $this->mydb->prepare($stmt);
if ($config === 1 || $config === 2) {
$mydb->bind_param("s",$options['where_value']);
}
if ($mydb->execute()) { /** If execute is good then get results */
$result = $mydb->get_result();
$payload = array();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
$payload[] = $row;
}
return $payload;
} /** End if results */
} /** End choose class method */
} /** End mydb Class */
$myDB = new mydb();
$agentArray = $myDB->choose('*','`agent`');
Used the php.net example and modified it to show a better example:
$mysqli = new mysqli('host', 'database', 'user', 'pass');
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!($stmt = $mysqli->prepare("SELECT ? FROM ?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!($res = $stmt->get_result())) {
echo "Getting result set failed: (" . $stmt->errno . ") " . $stmt->error;
}
for ($row_no = ($res->num_rows - 1); $row_no >= 0; $row_no--) {
$res->data_seek($row_no);
var_dump($res->fetch_assoc());
}
$res->close();
The very first result from the "Related" section on this page (Means it was offered to you while you were in struggle writing your question) offers a solution.
As a general rule, it is quite easy to find an answer to a question based on the error message. Only you need is not to stop at the very first search result but proceed a bit more.
However, on this function choose() of yours. I find it quite impractical, unsafe, and useless:
impractical because it doesn't let you to use SQL, but a very limited subset of it.
and also it makes your code extremely hard to understand.
unsafe because it does offer no protection for all the dynamical parts but where value only
useless because it can save you not that much to worth a mess.
Look, you think you saved yourself 2 words - SELECT and FROM.
$agentArray = $myDB->choose('*','`agent`',1,
array('where_comp' => 'name', 'where_value' -> "%bob%"));
yet you made this code hard to understand, hard to maintain and unable to run ever simplest JOIN. Why not to make it. Not to mention that actual code become longer than conventional SQL query:
$sql = 'SELECT * FROM `agent` WHERE name LIKE ?';
$agentArray = $myDB->query($sql, "%bob%");
which one is easier to read?
Adding an if statement to show the error correctly actually gives a mysql error response that can be used:
if (!($stmt = $mysqli->prepare("SELECT ? FROM ?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
Error response:
Prepare failed: (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
-- You can't pass identifiers through prepared-statements and you should only use it for values passed from user input.
OK I'll start with my code:
include('connect.php');
// Prepared statement, prepare
if (!($stmt = $mysqli->prepare("INSERT INTO funddata(ticker, priceDate, price) VALUES (?, ?, ?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
//Bind the parameters to the query
$csvData = array("","",""); //Initialise the $csvData array
$priceDate = date($csvData[1]);
$stmt -> bind_param("ssd", $csvData[0], $priceDate, $csvData[2]);
$file_handle = fopen($csvfile, "r");
while (!feof($file_handle) ) {
$csvData = fgetcsv($file_handle, 1024);
$priceDate = date($csvData[1]);
echo $csvData[0] . "; " . $priceDate . "; ". $csvData[2] . "<br/>";
//Run the insert statement
$stmt->execute();
}
fclose($file_handle);
This fails to insert the data into the database table, although it does result in a load of blank rows being inserted.
The csv data is being correctly read as evidenced by the echoing of it inside the loop.
Where have I gone wrong here?