Need help inserting into MySQL database table using PDO - php

The database table only contains the four fields that the query is attempting to insert into. For some reason I get the error: Query failed: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined.
I have troubleshot by echoing the output of the foreach loops and it always returns four items, I'm not sure what parameter isn't defined. I have also played around with including the field names in the $sql string as well as not including them. Same results either way. Please help if you can.
<?php
class DB {
private $_conn;
public function openDB() {
$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "password";
try {
$this->_conn = new PDO( $dsn, $username, $password );
$this->_conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo "Connection failed: " . $e->getMessage();
}
}
public function closeDB() {
$this->_conn = null;
}
public function selectData( $myQuery ) {
$rows = $this->_conn->query( $myQuery );
foreach ( $rows as $row ) {
echo "Index: " . $row['id'] . "<br />";
echo "Title: " . $row['title'] . "<br />";
}
}
public function insertData( $tableName ) {
$q = $this->_conn->prepare("DESCRIBE " . $tableName);
$q->execute();
$getFields = $q->fetchAll(PDO::FETCH_COLUMN);
$dbFieldCount = count( $getFields );
$implodedFields = implode( ", :", $getFields );
//$sql = "INSERT INTO " . $tableName . " ( " . implode( ", ", $getFields ) . " ) VALUES ( :" . $implodedFields . " )";
$sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";
echo "$sql<br />";
try {
$insert = $this->_conn->prepare( $sql );
foreach ( $getFields as $dbKey => $dbValue ) {
foreach( $_POST as $formKey => $formValue ) {
if ( $dbValue == 'id' ) {
$insert->bindValue( '\":' . $dbValue . '\"', null, PDO::PARAM_INT );
echo "$dbValue<br />";
break;
} else if ( is_int( $formValue ) && $dbValue == $formKey ) {
$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_INT );
echo "$formValue<br />";
break;
} else if ( is_string( $formValue ) && $dbValue == $formKey ) {
$insert->bindValue( '\":' . $dbValue . '\"', $formValue, PDO::PARAM_STR );
echo "$formValue<br />";
break;
}
}
}
$insert->execute();
} catch ( PDOException $e ) {
echo "Query failed: " . $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
if ($_POST) {
$conn = new DB();
$conn->openDB();
$conn->insertData( 'login' );
$conn->closeDB();
}
?>
<form action="#" method="POST" name="register">
<label for="username">Username</label><br />
<input type="text" id="username" name="username"><br />
<label for="password">Password</label><br />
<input type="password" id="password" name="password"><br />
<label for="email">Email Address</label><br />
<input type="text" id="email" name="email"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

$sql = "INSERT INTO " . $tableName . " VALUES ( :" . $implodedFields . " )";
Here you're adding all columns into your SQL statement, but later you only add values that are sent when the form is submitted. It's possible that you have columns in your database that aren't in the form, so you're coming up with a statement like:
INSERT INTO someTable VALUES (:id, :value1, :value2)
And then you only bind :id and :value1, leaving MySQL confused about what :value2 is supposed to be.

Related

Insert Images at Database PHPMYSQL

So im trying to upload/host images at my database but for some reason i cant archieve it.
Insert the Image:
<form method="post" action="actions/dados_insert.php" enctype="multipart/form-data">
<input type="file" name="imagem" />
</form>
dados_insert.php
<?php
if ( ! empty( $_POST ) ) {
$mysqli = new mysqli( 'localhost', 'root', '', 'valsil' );
$mysqli->set_charset("utf8");
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
$sql = "INSERT INTO dados ( id_proposta, quantidade, posicao, unitario, titulo, `desc`, imagem ) VALUES ( '{$mysqli->real_escape_string($_POST['id_proposta'])}', '{$mysqli->real_escape_string($_POST['quantidade'])}', '{$mysqli->real_escape_string($_POST['posicao'])}', '{$mysqli->real_escape_string($_POST['unitario'])}', '{$mysqli->real_escape_string($_POST['titulo'])}', '{$mysqli->real_escape_string($_POST['desc'])}', '{$mysqli->real_escape_string($_FILES['imagem'])}' )";
$insert = $mysqli->query($sql);
if ( $insert ) {
header("Location: ". $_SERVER['HTTP_REFERER']);
exit();
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
}
?>
Update the Image:
<form method="post" action="actions/dados_update.php?id=<?php echo $row['id']; ?>" enctype="multipart/form-data">
<input type="file" name="imagem" />
</form>
dados_update.php
<?php
if ( ! empty( $_POST ) ) {
$mysqli = new mysqli( 'localhost', 'root', '', 'valsil' );
$mysqli->set_charset("utf8");
$id = $_GET['id'];
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
$sql = "UPDATE dados SET quantidade = '{$mysqli->real_escape_string($_POST['quantidade'])}', posicao = '{$mysqli->real_escape_string($_POST['posicao'])}', unitario = '{$mysqli->real_escape_string($_POST['unitario'])}', titulo = '{$mysqli->real_escape_string($_POST['titulo'])}', `desc` = '{$mysqli->real_escape_string($_POST['desc'])}', imagem = '{$mysqli->real_escape_string($_FILES['imagem'])}' WHERE id =".$id;
$insert = $mysqli->query($sql);
if ( $insert ) {
header("Location: ". $_SERVER['HTTP_REFERER']);
exit();
} else {
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
}
?>
I would appreciate any help, theres something missing for sure, first time trying to upload images and already readed tutorials but still couldnt get the answer.
Cumps.

Inputs array from while loop, passing $_POST for each input

<form role="form" autocomplete="off" action="includes/functions/fisa-init.php" method="POST">
<?php
connectDB();
$query = mysqli_query($mysqli, "SELECT * FROM `optionale`") or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($query))
{
?>
<span><?php echo $row['denumire']; ?></span>
<input type="text" name="nrBucati[]">
<input type="hidden" value="<?php echo $row['cod']; ?>" name="codProdus[]">
<?php } ?>
</form>
In the while loop I get an array for input name="nrBucati[]" and input name="codProdus[]".
I have the query:
$stmt3 = $mysqli->prepare("
UPDATE
`stocuri`
SET
`cantitate` = `cantitate` - ?
WHERE `cod` = ?
");
$stmt3->bind_param("is", $bucata, $cod);
// set parameters and execute
foreach( $_POST['nrBucati'] as $bucata ) {
return $bucata;
}
foreach( $_POST['codProdus'] as $cod ) {
return $cod;
}
if (!$stmt3->execute())
{
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
$stmt3->close();
I cannot manage to take all the input array values through $_POST. Detailed in:
While loop - Only one input from many others is sending a value through POST
How to get each input value from the arrays nrBucati[] and codProdus[] from HTML, through POST?
Something like this to properly assign/pair up your two params and then execute your query call from within the loop.
foreach( $_POST['nrBucati'] as $id => $bucata ) {
$cod = $_POST['codProdus'][$id];
if (!$stmt3->execute())
{
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
}
Run a foreach and prepare your data inside foreach loop:
// Get posted data and execute
foreach( $_POST['nrBucati'] as $key=>$bucata ) {
$cod = $_POST['codProdus'][$key]; // For object change this to $_POST['codProdus']->$key;
$stmt3= $mysqli->prepare("UPDATE `stocuri` SET `cantitate` = `cantitate` - ?
WHERE `cod` = ? ");
$stmt3->bind_param("is", $bucata, $cod);
if (!$stmt3->execute()){
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
$stmt3->close();
}

PHP PDO Class and Smarty

Hello so currently I am using a php pdo class for my database connection and here is the code
class db extends PDO {
private $error;
private $sql;
private $bind;
private $errorCallbackFunction;
private $errorMsgFormat;
public function __construct($dsn='', $user='', $passwd='') {
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
if (empty($dsn)) {
$dsn = 'mysql:host=localhost;dbname=db_disaster';
}
if (empty($user)) {
$user = 'root';
}
try {
parent::__construct($dsn, $user, $passwd, $options);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
private function debug() {
if(!empty($this->errorCallbackFunction)) {
$error = array("Error" => $this->error);
if(!empty($this->sql))
$error["SQL Statement"] = $this->sql;
if(!empty($this->bind))
$error["Bind Parameters"] = trim(print_r($this->bind, true));
$backtrace = debug_backtrace();
if(!empty($backtrace)) {
foreach($backtrace as $info) {
if($info["file"] != __FILE__)
$error["Backtrace"] = $info["file"] . " at line " . $info["line"];
}
}
$msg = "";
if($this->errorMsgFormat == "html") {
if(!empty($error["Bind Parameters"]))
$error["Bind Parameters"] = "<pre>" . $error["Bind Parameters"] . "</pre>";
$css = trim(file_get_contents(dirname(__FILE__) . "/error.css"));
$msg .= '<style type="text/css">' . "\n" . $css . "\n</style>";
$msg .= "\n" . '<div class="db-error">' . "\n\t<h3>SQL Error</h3>";
foreach($error as $key => $val)
$msg .= "\n\t<label>" . $key . ":</label>" . $val;
$msg .= "\n\t</div>\n</div>";
}
elseif($this->errorMsgFormat == "text") {
$msg .= "SQL Error\n" . str_repeat("-", 50);
foreach($error as $key => $val)
$msg .= "\n\n$key:\n$val";
}
$func = $this->errorCallbackFunction;
$func($msg);
}
}
public function delete($table, $where, $bind="") {
$sql = "DELETE FROM " . $table . " WHERE " . $where . ";";
$this->run($sql, $bind);
}
private function filter($table, $info) {
$driver = $this->getAttribute(PDO::ATTR_DRIVER_NAME);
if($driver == 'sqlite') {
$sql = "PRAGMA table_info('" . $table . "');";
$key = "name";
}
elseif($driver == 'mysql') {
$sql = "DESCRIBE " . $table . ";";
$key = "Field";
}
else {
$sql = "SELECT column_name FROM information_schema.columns WHERE table_name = '" . $table . "';";
$key = "column_name";
}
if(false !== ($list = $this->run($sql))) {
$fields = array();
foreach($list as $record)
$fields[] = $record[$key];
return array_values(array_intersect($fields, array_keys($info)));
}
return array();
}
private function cleanup($bind) {
if(!is_array($bind)) {
if(!empty($bind))
$bind = array($bind);
else
$bind = array();
}
return $bind;
}
public function insert($table, $info) {
$fields = $this->filter($table, $info);
$sql = "INSERT INTO " . $table . " (" . implode($fields, ", ") . ") VALUES (:" . implode($fields, ", :") . ");";
$bind = array();
foreach($fields as $field)
$bind[":$field"] = $info[$field];
return $this->run($sql, $bind);
}
public function run($sql, $bind="") {
$this->sql = trim($sql);
$this->bind = $this->cleanup($bind);
$this->error = "";
try {
$pdostmt = $this->prepare($this->sql);
if($pdostmt->execute($this->bind) !== false) {
if(preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->sql))
return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
elseif(preg_match("/^(" . implode("|", array("delete", "insert", "update")) . ") /i", $this->sql))
return $pdostmt->rowCount();
}
} catch (PDOException $e) {
$this->error = $e->getMessage();
$this->debug();
return false;
}
}
public function select($table, $where="", $bind="", $fields="*") {
$sql = "SELECT " . $fields . " FROM " . $table;
if(!empty($where))
$sql .= " WHERE " . $where;
$sql .= ";";
return $this->run($sql, $bind);
}
public function setErrorCallbackFunction($errorCallbackFunction, $errorMsgFormat="html") {
//Variable functions for won't work with language constructs such as echo and print, so these are replaced with print_r.
if(in_array(strtolower($errorCallbackFunction), array("echo", "print")))
$errorCallbackFunction = "print_r";
if(function_exists($errorCallbackFunction)) {
$this->errorCallbackFunction = $errorCallbackFunction;
if(!in_array(strtolower($errorMsgFormat), array("html", "text")))
$errorMsgFormat = "html";
$this->errorMsgFormat = $errorMsgFormat;
}
}
public function update($table, $info, $where, $bind="") {
$fields = $this->filter($table, $info);
$fieldSize = sizeof($fields);
$sql = "UPDATE " . $table . " SET ";
for($f = 0; $f < $fieldSize; ++$f) {
if($f > 0)
$sql .= ", ";
$sql .= $fields[$f] . " = :update_" . $fields[$f];
}
$sql .= " WHERE " . $where . ";";
$bind = $this->cleanup($bind);
foreach($fields as $field)
$bind[":update_$field"] = $info[$field];
return $this->run($sql, $bind);
}
}
And I am also using Smarty template engine for me to separate my presentation with the application code. So I am now doing a CRUD, and in my edit.php this what it looks like
require_once('header.php');
include('class.db.php');
$db = new db();
$id = $_GET['id'];
$bind = array(
":id" => $id
);
$results = $db->select("Contacts", "ContactID = :id", $bind);
$app->assign('contact', $results);
$app->display('edit.tpl');
My problem is I am still using foreach to output data/s in the textbox in my edit.tpl
{include file="header.tpl" title="Edit Contact"}
{foreach $contact as $r}
<form action="edit.php" method="POST">
Name: <input type="text" name="txt_name" value="{$r.ContactName}"> <br />
Contact: <input type="text" name="txt_contact" value="{$r.ContactNumber}"> <br />
<input type="submit" name="edit_btn" value="Edit Contact">
</form>
{/foreach}
{include file="footer.tpl"}
Is there a better way of doing this? I just want to use foreach in displaying all data, not by just one data from my id
The thing is your db class 'select' method always makes use of PDO fetchAll, if your action is based on a single row only then why not pass just the one result to the template?
$results = $db->select("Contacts", "ContactID = :id", $bind);
if (empty($results)) {
throw new Exception("No contact found");
}
$app->assign('contact', $results[0]); // only pass the one result to the template
$app->display('edit.tpl');
And in the template file, you can simply remove the foreach and since the result is guaranteed to be there already, no need for any checking:
{include file="header.tpl" title="Edit Contact"}
<form action="edit.php" method="POST">
Name: <input type="text" name="txt_name" value="{$contact.ContactName}"> <br />
Contact: <input type="text" name="txt_contact" value="{$contact.ContactNumber}"> <br />
<input type="submit" name="edit_btn" value="Edit Contact">
</form>
{include file="footer.tpl"}

How to build a dynamic MySQL INSERT statement with PHP

Hello
This part of a form is showing columns names from mysql table (names of applications installed on a computer) and creating a form with YES/NO option or input type="text" box for additional privileges to a application..
How can I insert it back to a mysql table using POST and mysql_query INSERT INTO?????
Quantity of columns is changing because there is another form for adding applications with/without privileges..
<tr bgcolor=#ddddff>';
//mysql_query for getting columns names
$result = mysql_query("SHOW COLUMNS FROM employees") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
//exclude these columns bcs these are in other part of form
if($row[0] == 'id' || $row[0] == 'nameandsurname' || $row[0] == 'department'
|| $row[0] == 'phone' || $row[0] == 'computer' || $row[0] == 'data')
continue;
echo '<td bgcolor=#ddddff>'.$row[0].'<br />';
if (stripos($row[0], "privileges") !== false) {
echo '<td bgcolor=#ddddff><p><a class=hint href=#>
<input type="text" name="'.$row[0].'">
<span>Privileges like "occupation" or "like someone"</span></a></p></td></tr>';
}
else
{
echo '<td bgcolor=#ddddff align=center><select name="'.$row[0].'">
<option value = "No">No
<option value = "Yes">Yes
</td>
</tr>';
}
}
trim($_POST); // ????
$query = "INSERT INTO 'employees' VALUES (??)"; // ????
Because you're not inserting ALL columns, you need to dynamically build an insert statement that will specify the columns you're inserting into.
First, create an array of the columns you want to use. Use this both to generate your form and to retrieve the values
$exclude = array("id", "nameandsurname", "departument", "phone", "computer", "date");
$result = mysql_query("SHOW COLUMNS FROM employees") or die(mysql_error());
$columns = array();
while ($row = mysql_fetch_array($result)) {
if (!in_array($row[0], $exclude) {
$columns[] = $row[0];
}
}
Render your form from the $columns array:
foreach ($columns as $column) {
echo '<tr><td bgcolor="#ddddff">'.$column.'<br />';
if (stripos($column, "privileges") !== false) {
echo '<p><a class="hint" href="#">
<input type="text" name="'.$column.'">
<span>Privileges like "occupation" or "like someone"</span></a>';
} else {
echo '<select name="'.$column.'">
<option value = "No">No
<option value = "Yes">Yes
</select>';
}
echo '</td></tr>';
}
Then, dynamically build your INSERT string from the posted values for those columns. Be sure to protect against SQL injection:
$keys = array();
$values = array();
foreach ($columns as $column) {
$value = trim($_POST[$column]);
$value = mysql_real_escape_string($value);
$keys[] = "`{$column}`";
$values[] = "'{$value}'";
}
$query = "INSERT INTO 'employees' (" . implode(",", $keys) . ")
VALUES (" . implode(",", $values) . ");";
Note: this will work better if you select from INFORMATION_SCHEMA.COLUMNS so that you can know the type of column you're inserting into. That way, you won't have to quote everything.
<html>
<body>
<form action="dynamicinsert.php" method="POST" >
user name:<br>
<input type="text" id="username" name="username">
<br><br>
first name:<br>
<input type="text" id="firstname" name="firstname">
<br><br>
password:<br>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" name="submit" value="add" />
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "you_DB_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function insertqueryfunction($dbfield,$table) {
$count = 0;
$fields = '';
foreach($dbfield as $col => $val) {
if ($count++ != 0) $fields .= ', ';
$col = addslashes($col);
$val = addslashes($val);
$fields .= "`$col` = '$val'";
}
$query = "INSERT INTO $table SET $fields;";
return $query;
}
if(isset($_POST['submit']))
{
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
$username_form = $_POST['username'];
$firstname_form = $_POST['firstname'];
$password_form = $_POST['password'];
$you_table_name = 'you_table_name';
$dbfield = array("username"=>$username_form, "firstname"=>$firstname_form,"password"=>$password_form);
$querytest = insertqueryfunction($dbfield,'you_table_name');
if ($conn->query($querytest) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>

PHP within an Iframe not working in IE

I have a program, that searches a database from a PHP file, linking back to the some file with the output.
It works perfectly in all browsers, excluding IE. I have no idea why.
Here is my code:
<?php
if( isset( $_POST['schoolname'] ) && strlen( trim( $_POST['schoolname'] ) ) > 0 )
{
$school = filter_input(INPUT_POST, 'find', FILTER_SANITIZE_STRING);
$school = $_POST['schoolname'];
#connecting to the database
$conn = mysql_connect("localhost", "root");
mysql_select_db("finalproject");
$sql = "select * from presentations where school like '%$school%'";
$result = mysql_query($sql, $conn) or die(mysql_error());
#this is the array that stores and displays the results of the search
if ( mysql_num_rows($result) >0)
{
while ($newArray = mysql_fetch_array($result))
{
$school = $newArray['school'];
$date = $newArray['date'];
$place = $newArray['place'];
$time = $newArray['time'];
echo $school . ", " . $place . ", " . $date . ", " . $time . "<br />" . "<br />";
}
}
else
{
echo "Record not found" . "<br />" . "<br />";
}
mysql_close($conn);
}
?>
<!-- The form in which the search happens -->
<form action=" " method="post">
School's name: <input type="text" name="schoolname">
<input type="submit" name="button" value="Search">
</form>
This is just my code for within the IFrame.

Categories