I've got a working insert for a single input field but when I try to add a couple more it seems to break everything. I have a database connection working fine and including that correctly at the top of the page when I change the "isset" to have the 3 columns it breaks.
This is my set statement;
if(isset($_POST['title, question, tags']))
{
$success = insertData('questions', 'title', $_POST['title']);
$success = insertData('questions', 'question', $_POST['question']);
$success = insertData('questions', 'tags', $_POST['tags']);
if(!$success)
echo 'Sorry failed :(';
}
The function I call from a functions php file;
function insertData($tablename, $columnName, $value)
{
$sql = 'INSERT into '.$tablename.'('.$columnName.') VALUES(:Value)';
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql);
$statement->bindValue(":Value", $value, PDO::PARAM_STR);
$bReturn = false;
try
{
$statement->execute();
$bReturn = true;
}
catch(PDOExecption $e)
{
echo $e->getMessage();
}
return $bReturn;
}
Does anyone know where I'm going wrong here?
if(isset($_POST['title, question, tags']))
Is not correct syntax
instead You can do:
if(isset($_POST['title']) && isset($_POST['question']) && isset($_POST['tags']))
or even
if(isset($_POST['title'], $_POST['question'], $_POST['tags']))
It would be easier to do execute it without binding:
insertData
function insertData($tablename, $params){
//build query string
$column_string = implode(',', array_keys($params));
$value_string = implode(',', array_fill(0, count($params), '?'));
$sql_string = "INSERT INTO {$tablename} ({$columnString}) VALUES ({$value_string})";
//prepare query
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql_string);
//execute query
$success = $statement->execute(array_values($params));
//return boolean success
return $success;
}
But If you really need to bind, you can do it the following way:
function insertDataBind($tablename, $params){
//build query string
$column_string = implode(',', array_keys($params));
$value_string = implode(',:', array_keys($params));
$sql_string = "INSERT INTO {$tablename} ({$column_string}) VALUES (:{$value_string})";
//prepare query
$mysqlConnection = getConnection();
$statement = $mysqlConnection->prepare($sql);
//bind
foreach($params as $key=>$value){
$statement->bindValue($key, $value);
}
//execute query
$success = $statement->execute();
//return boolean success
return $success;
}
usage:
if(isset($_POST['title'], $_POST['question'], $_POST['tags'])){
$params = array('title' => $_POST['title'],
'question'=>$_POST['question'],
'tags'=>$_POST['tags']
);
$success = insertData('questions', $params);
if(!$success)
echo 'Sorry failed :(';
}
Related
I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;
How can you insert with PDO then return the lastInsertId() that was created? This can be done inside the function, but I either way I would like to get the lastInsertId() outside the function.
function insert_PDO($item1, $item2){
$params = array(
":item1" => $item1 ,
":item2" => $item2
);
$sql = "INSERT INTO table (column1, column2)
VALUES (:item1, :item2)
";
//return $this->insert($sql, $params); //this one works
//now trying this, want to return
$insertitems = $this->insert($sql, $params);
$item_ID = $this->lastInsertId();
return ($insertitems, $item_ID) ; //does not work
}
protected function insert($sql, $params)
{
$stmt = $this->dbh->prepare($sql);
return $stmt->execute($params);
}
// I tried this too with the original insert:
$results = $createInsert -> insert_PDO($item1, $item2);
$lastid = $results[0];
foreach($results1 as $row){
$auditVID = $row[ID];
$auditVID = $row[0];
}
Statement
return ($insertitems, $item_ID) ;
will cause syntax error.
If you want to return several values - use array:
$insertitems = $this->insert($sql, $params);
$item_ID = $this->lastInsertId();
return array($insertitems, $item_ID) ;
// or for newer php versions:
return [$insertitems, $item_ID];
So I'm trying to do a conditional update but I seem to be having problems with binding the data with the statement.
function:
function updateEditor($email, $first, $last, $id){
global $DBH;
$response = false;
$upemail = "";
$upfirst = "";
$uplast = "";
$stmt = "SELECT memEmail, memFirst, memLast FROM MEMBER WHERE memID = :id";
try{
$STH = $DBH->prepare($stmt);
$STH->bindParam(':id', $id);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
$row = $STH->fetch();
if($row['memEmail'] != $email){ $upemail = $email;}
if($row['memFirst'] != $first){ $upfirst = $first;}
if($row['memLast'] != $last){ $uplast = $last;}
}catch(PDOException $e) {
echo $e->getMessage() . "first";
}
$stmt .= "UPDATE MEMBER SET ";
if(!empty($upemail)){
$stmt .= "memEmail = :memEmail";
if(!empty($upfirst) || !empty($uplast)){
$stmt .= ", ";
}
}
if(!empty($upfirst)){
$stmt .= "memFirst = :memFirst";
if(!empty($uplast)){
$stmt .= ", ";
}
}
if(!empty($uplast)){
$stmt .= "memLast = :memLast";
}
if(empty($upemail) && empty($upfirst) && empty($uplast)){
return false;
}else{
$stmt .= " WHERE memID = :id";
}
try{
$STH = $DBH->prepare($stmt);
if(!empty($upemail)){$STH->bindParam(':memEmail', $upemail);}else{$STH->bindParam(':memEmail', $row['memEmail']);}
if(!empty($upfirst)){$STH->bindParam(':memFirst', $upfirst);}else{$STH->bindParam(':memFirst', $row['memFirst']);}
if(!empty($uplast)){$STH->bindParam(':memLast', $uplast);}else{$STH->bindParam(':memLast', $row['memLast']);}
$STH->bindParam(':id', $id);
$STH->execute();
$STH->setFetchMode(PDO::FETCH_ASSOC);
$response = true;
}catch(PDOException $e) {
echo $e->getMessage() . "second";
$response = $e->getMessage() . "second";
}
return $response;
}
I have tried putting the variables into the statement, using ?, and the code above so far. The error I keep getting is:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Here:
$stmt .= "UPDATE MEMBER SET ";
you append the UPDATE to the previous $stmt string. You'll end up with:
$stmt = "SELECT memEmail, memFirst, memLast FROM MEMBER WHERE memID = :idUPDATE MEMBER SET "; // and the rest
reulting in one identifier more (:idUPDATE).
Remove the . to start a new query in this string.
$stmt = "UPDATE MEMBER SET ";
Note:
You are making this way too complicated. Skip the checks for empty values, just update all columns when you update a dataset, you don't gain anything by checking what has changed and what hasn't first.
Besides #Gerald Schneider answer, you are setting the param in both cases (if/else)
if(!empty($upemail)){$STH->bindParam(':memEmail', $upemail);}else{$STH->bindParam(':memEmail', $row['memEmail']);}
But are defining the parameters only in one case
if(!empty($upemail)){
$stmt .= "memEmail = :memEmail";
if(!empty($upfirst) || !empty($uplast)){
$stmt .= ", ";
}
}
if(!empty($upfirst)){
$stmt .= "memFirst = :memFirst";
if(!empty($uplast)){
$stmt .= ", ";
}
}
if(!empty($uplast)){
$stmt .= "memLast = :memLast";
}
There's no else condition
I would like to write a database connection class and I dont understand how I have to write the select method with bind_param-s. Here is the full code. And here the part of the code where I need the help:
public function select($sql){
$db = $this->connect(); //This methos connect to the DB
$stmt = $db->prepare($sql);
if($stmt === false){ //If the prepare faild
trigger_error("Wrong SQL", E_USER_ERROR);
}
$error = $stmt->bind_param("i", $id);
if($error){
return "Error: ".$stmt->error, $stmt->errno;
}
$err = $stmt->execute();
if($error){
return "Error: ".$stmt->error, $stmt->errno;
}
$result = $stmt->bind_result($id);
$stmt->close();
$dbConnection->closeConnection($db);
return $result;
}
I need to got it parameters or how can I slove it?
You need to pass your values into this function too. And eventually bind them into prepared statement.
Optionally you can pass string with types, but by default all "s" will do.
Also remember that you should connect only ONCE per script execution. and then use one single connection all the way throughout your code.
And get rid of all these error checks. Set mysqli in exception mode instead.
public function q($sql, $values = array(), $types = NULL)
{
$stm = $this->mysql->prepare($sql);
if (!$types)
{
$types = str_repeat("s", count($values));
}
if (strnatcmp(phpversion(),'5.3') >= 0)
{
$bind = array();
foreach($values as $key => $val)
{
$bind[$key] = &$values[$key];
}
} else {
$bind = $values;
}
array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);
$stm->execute();
return $stm->get_result();
}
so it can be used like this
$res = $db->q("SELECT name FROM users WHERE id=?", [$id]);
or
$res = $db->q("SELECT name FROM users WHERE id=?", [$id], "i");
your other functions have to be changed as well.
class DB{
public $con;
function __construct()
{
$this->con = new mysqli("localhost", "root", "", "proba_fferenc");
}
public function select(...)
{
// as shown above
}
}
For example, I have a couple of tables in my database, e.g., user, product, etc. Fro every table, I have at least an associated class with a couple of methods, such as addUser, updateUserName, updateUserPassword, etc. For every method, I need to prepare the SQL when using PDO, which looks like this:
$sql = "INSERT INTO `user`
(`id`,`username`,`password`,`log`)
VALUES
(:id, :username, :password, :log)";
Then I store the values in an array like this:
$array = array('id'=>$id, 'username'=>$username, 'password'=>$password, 'log'=>$log);
Then I use the PDO thing:
$pdo = new PDO($dsn, $user, $password);
$mysql = $pdo->prepare($sql);
$mysql->execute($array);
So it seems that for all different methods inside the User class, I need to do this "prepare" thing. Isn't it too tedious? Is there a more efficient way to do so, especially the part where I store the values in an array considering there exist a table with many columns in which case I would end up with a very long prepare sentence?
Since Your own is insert and update try these
//to query the database with prepared statements
public function query ($sql, $parameters = array()) {
//setting error to false to prevent interferance from previous failed queries
$this->_error = false;
//prepare SQL statement
if ($this->_query = $this->_pdo->prepare ($sql)) {
//checking to see whether any parameters were submitted along
if (count($parameters)) {
//setting the initial position for the binding values
$position = 1;
//getting the individual parameters and binding them with their respective fields
foreach ($parameters as $param) {
$this->_query->bindValue ($position, $param);
$position++;
}
}
}
//executing the sql
if ($this->_query->execute()) {
//getting the number of rows returned
$this->_count = $this->_query->rowCount();
//keeping the results returned
$this->_results = $this->_query->fetchAll (PDO::FETCH_OBJ);
} else {
$this->_error = true;
}
//returning all values of $this
return $this;
}
//to insert data into a prescribed table
public function insert ($table, $parameters = array()) {
//checking if the $fields are not empty
if (count($parameters)) {
//making the keys of the array fields
$fields = array_keys ($parameters);
//creating the to-bind-values in the form (?, ?, ...)
$values = '';
$x = 1;
foreach ($parameters as $field => $value) {
//$value is different from $values
$values .= '?';
if ($x < count($parameters)) {
$values .= ', ';
$x++;
}
}
//generating $sql
$sql = "INSERT INTO `{$table}` (`".implode ('`, `', $fields)."`) VALUES ({$values})";
//executing the sql
if (!$this->query($sql, $parameters)->error()) {
return true;
}
}
return false;
}
//to update data in a prescribed table
public function update ($table, $id = null, $parameters = array()) {
//checking that $parameters is not an empty array
if (count($parameters)) {
$set = '';
$x = 1;
foreach ($parameters as $field => $value) {
$set .= "`{$field}` = ?";
if ($x < count($parameters)) {
$set .= ', ';
$x++;
}
}
if ($id) {
//generating query
$sql = "UPDATE `{$table}` SET {$set} WHERE `id` = {$id}";
} else {
$sql = "UPDATE `{$table}` SET {$set} WHERE 1";
}
//executing the query
if (!$this->query($sql, $parameters)->error()) {
return true;
}
}
return false;
}