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 :)
Related
I tried to update a row in table showtable
Bugupdate
By using the php code below, binding a bugID to a SQL UPDATE statement to update the row I want to but it doesn't seem to work, is it the problem lie in my SQL statement ?
$id = $_GET['update'];
$games = htmlentities($_POST['games']);
$version = htmlentities($_POST['version']);
$platform = htmlentities($_POST['platform']);
$frequency = htmlentities($_POST['frequency']);
$proposal = htmlentities($_POST['proposal']);
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?,Platform=?,Frequency=?,Proposed solution=? WHERE BugID= " .$id;
if ($stmt = mysqli_prepare($DBconnect, $SQLstring2)) {
mysqli_stmt_bind_param($stmt,'sssss', $games, $version, $platform, $frequency, $proposal);
$QueryResult2 = mysqli_stmt_execute($stmt);
if ($QueryResult2 === FALSE) {
echo "<p>Unable to execute the query.</p>"
. "<p>Error code "
. mysqli_errno($DBconnect)
. ": "
. mysqli_error($DBconnect)
. "</p>";
} else {
echo "<h1> Thank you for your contribution";
}
mysqli_stmt_close($stmt);
}
mysqli_close($DBconnect);
Try to rename Proposed solution column to Proposed_solution and adapte the sql query like this :
$SQLstring2 = "UPDATE " .$TableName. " SET Game=?,Version=?, Platform=?, Frequency=?, Proposed_solution=? WHERE BugID= " .$id;
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.
I am new to using prepared statement with PHP. I am trying to get the value of "full_name"... So far I am stuck over here. Can anyone please help figure this out? Thanks!
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$row = $stmnt->fetch();
You need to use bind_result to bind variables to the columns you want. Then each time you call fetch(), those variables will be updated with the next row's values. fetch() with mysqli does not return you the row/result.
This means you cannot use SELECT *. You need to specify which fields you want.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT full_name FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$stmnt->bind_result($full_name);
$stmnt->fetch();
echo $full_name;
Or, if you have the mysqlnd driver installed, you can use get_result() to get a result set just like if you had ran a normal query, not a prepared statement.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$result = $stmnt->get_result();
$row = $result->fetch_assoc();
echo $row['full_name'];
This question already has answers here:
Using fetch_assoc on prepared statements
(3 answers)
Closed last year.
I am able to get the result from a standard SQL query however when it comes to prepared statements I am fine up until it comes to getting the result from the query.
As background the query will result with more than one row.
$sql = "SELECT * FROM blog WHERE ID=?";
if (!$stmt = $con -> prepare($sql)) {
echo "Prepare failed: (" . $con->errno . ") " . $con->error;
}
if (!$stmt->bind_param("i", $_GET["ID"])) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
while($row = $stmt->fetch_assoc()){
$blog_title = $row['title'];
$blog_body = $row['body'];
$blog_blurb = $row['blurb'];
$blog_date = $row['posted'];
$blog_tags = $row['tags'];
}
This results in
Fatal error: Call to undefined method mysqli_stmt::fetch_assoc()
However, I have tried what was outlined in the PHP manual but have not succeeded.
Here is better way to do it.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mydatabase = new mysqli('localhost', 'root', '', 'database');
$id = $_GET['id'];
$stmt = $mydatabase->prepare("SELECT * FROM `blog` where ID = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result(); //get the results
while ($row = $result->fetch_assoc()) {
echo $row['whatever']; //do whatever here
}
If get_result() doesn't exist in your installation, use this:
$stmt->bind_result($column1, $column2);
while ($stmt->fetch()) {
echo $column1;
echo $column2;
}
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.