I tried using LAST_INSERT_ID() when getting the last id of the autoincrement primary key column but I get EOF exception :
function add($tab) {
$champs= "";
$value = "";
$separateur ="";
$tab["commande_date"] = convertDateFormat5($tab["commande_date"]);
foreach ($tab as $k => $v){
if ($k == "salle_code" || $k == "table_code")
continue;
$champs .= $separateur . $k;
$value .= $separateur . "'" . $v . "'";
$separateur = ",";
}
$champs = '('.$champs.')';
$value = '('.$value.')';
$sSQL = "
INSERT INTO Commande $champs
VALUES $value
";
$query = new Query($sSQL,$this->getDI());
$ret = $query->execute();
$sSQL = "SELECT LAST_INSERT_ID() as last_id";
$queryId = new Query($sSQL,$this->getDI());
return $queryId->execute();
}
So how to get the last id with Phalcon ?
The way you are handling this is fairly anti-MVC and you leave a lot of the Phalcon functionality on the table. You should have a database model named Commande which should be created something like:
$comande = new Commande();
then you can assign values like:
$comande->field1 = "hello";
$comande->adifferentfield = "world";
...
You'd then follow that up with:
$comande->save(); //yes I am aware we should test for success
Then you could access your key field, which would be populated automatically, something like:
print $comande->id;
You're missing out on a lot of the error handling and validation going about it the way you are.
$yourModel = new YourModel();
$yourModel->save() // Or create();
$newId = $yourModel->getWriteConnection()->lastInsertId();
I think it's easier in this way. Hope it's helpful.
you can use the lastInsertId() function
$sSQL = "INSERT INTO Commande $champs VALUES $value ";
$query = new Query($sSQL,$this->getDI());
$ret = $query->execute();
$lastId = $query->lastInsertId();
Update
Here is an example of inserting and getting back the lastinsert id.
$success = $connection->insert(
"robots",
array("Astro Boy", 1952),
array("name", "year")
);
//Getting the generated id
$id = $connection->lastInsertId();
I think this might help you.
In controller when you save:
if ($client->save() == false) {
foreach ($client->getMessages() as $message) {
$this->flash->error($message);
}
return $this->forward('clients/new');
}
// Get new client ID and redirect to new client
$this->response->redirect("client/page/$client->id");
$this->view->disable();
Related
Trying to create a function that would be used to update any row of any table, but I'm getting trouble getting into it.
Data sent in array where the array index is the field name in table and the value is the new value for that index.
For examplpe:
$args["name"] = "NewName";
$args["city"] = "NewCity";
$args["id"] = 4; // row ID to update
What I got:
function create_update_query($table, $keys){
$keys = array_map('escape_mysql_identifier', $keys);
$table = escape_mysql_identifier($table);
$updates = "";
$count = 0;
foreach($keys as $index => $value){
if($index != "id"){
$count++;
if($count == count($keys)-1){
$updates = $updates . "$index = ?";
}else{
$updates = $updates . "$index = ?,";
}
}
}
return "UPDATE $table SET $updates WHERE id = ? LIMIT 1";
}
After that, I have the function to really do the query:
function crud_update($conn, $table, $data){
$sql = create_update_query($table, array_keys($data));
if(prepared_query($conn, $sql, array_values($data))){
$errors [] = "OK";
}else{
$errors [] = "Something weird happened...";
}
}
The function that makes the prepared statement itself:
function prepared_query($mysqli, $sql, $params, $types = ""){
$types = $types ?: str_repeat("s", count($params));
if($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo "<br/>".$error;
}
}
When trying to submit the data with the following criteria:
$args['name'] = "Novo Nome";
$args['field'] = "New Field";
$args['numaro'] = 10101010;
$args['id'] = 4;
//create_update_query("teste_table", $args);
crud_update($link, "teste_table", $args);
Have an error:
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 '1 = ?,2 = ?,3 = ? WHERE id = ? LIMIT 1' at line 1
But if I echo the query created by create_update_query it seems ok:
UPDATE `teste_table` SET name = ?,field = ?,numaro = ? WHERE id = ? LIMIT 1
Any help would be appreciated.
Thanks.
The problem is that as you pass the keys to create_update_query() as
create_update_query($table, array_keys($data));
Using array_keys() will just take the key names, so the $keys parameter is just a list of the field names as something like ...
Array(
0=> 'name',
1 =>'field',
2 =>'numaro'
)
You then extract the data using
foreach($keys as $index => $value){
and build your SQL with
$updates = $updates . "$index = ?";
so at this point, the indexes are the numeric value, so change these lines to...
$updates = $updates . "$value = ?";
which is the name of the field.
With the various other changes, I would suggest the code should be...
foreach($keys as $value){
if($value != "id"){
$updates = $updates . "$index = ?,";
}
}
$updates = rtrim($updates, ",");
return "UPDATE $table SET $updates WHERE id = ? LIMIT 1";
I have searched around the web but no luck.
Am new to SQLSRV and i was migrating from PHP MySQL to PHP SQL and am having trouble inserting data from a form as some fields are optional which makes the column number vary. I need help on how i can insert when the column number varies.
thank you
here is how my insert code looks like
// sql fields and values for main table
$in_fields = array();
$in_values = array();
// prepare insertion
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
}
}
// prepare sql stmt
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES ()";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}
The executeSql function looks like this
function executeSql($sql, $params) {
global $conndb;
$rs = sqlsrv_query($conndb, $sql, $params)or die("Db query error.<br />".print_r(sqlsrv_errors(), true));
return !$rs ? false : true;
}
You need to add placeholder values (?) in the VALUES part of your query, you will need a placeholder for every value you pass through - i.e. for every value in $in_values.
To do this you could have another array, that will just have a number of ? as values, and then, like you have done for the fields, implode the array into the VALUES. Like so:
$in_fields = array();
$in_values = array();
$placeholders = array(); // new array
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
// add a placeholder to the array
$placeholders[] = "?";
}
}
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES (" . implode(",", $placeholders) . ")";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}
$value = $_POST['directions'];
$value2 = $_POST['inventory'];
$value3 = $_POST['item'];
$value4 = $_POST['vendor'];
$sql = "INSERT INTO a1 (directions,inventory,item,vendor) VALUE ('$value','$value2','$value3','$value4')";
Right now I'm having a mysql db get updated via what I type in a textbook from a separate page. However where it says "INSERT INTO a1" id like to make "a1" be a variable like "$table" I define from the same page I type all the other values in
The question need to be more clear, but from my understanding, you can use something like this code :
// should be defined like this inside each page.
$table = mysql_real_escape_string($_POST['tablename']);
$params = array();
foreach($_POST as $key => $val){
if($key!='tablename'){
$params[]= "$key='".mysql_real_escape_string($val)."'";
}
}
if(count($params) > 0) {
$params = implode(",",$params);
$sql = "INSERT INTO $table SET $params";
} else {
die "Error submitting the data!";
}
the problem is my function insert inserts my record in two rows.
this is my code to connect to database in a file named :
connect.php
<?php
try{
$db = new PDO("mysql:host=localhost;dbname=NPD" , "root" , "");
echo "connected";
}
catch(Exception $e){
echo $e->getMessage();
}
this is my database class in a file
database.php
<?php
require 'connect.php';
class DB {
public function insertInto($tableName , $info){
global $db;
foreach ($info as $coloumnName => $coloumnValue) {
$stmt = $db->prepare("INSERT INTO $tableName ($coloumnName) VALUES ('$coloumnValue') ");
$stmt->execute();
}
}
}
$da = new DB;
$da->insertInto('tableOne',array('name' => 'lolo' , 'deg' => '100'));
the result in the database is :
tableOne
how can to make the insert function inserts my record in one row.
note : i want to insert any number of columns and values.
try to do something like this:
$arr = array('name' => 'lolo' , 'deg' => '100');
$columns=array_keys($arr);
$values=array_values($arr);
$str="INSERT INTO $tableName (".implode(',',$columns).") VALUES ('" . implode("', '", $values) . "' )";
echo $str;//your sql
// $stmt = $db->prepare($str);
// $stmt->execute();//uncomment to execute
Like this but there are some concerns ( also I haven't tested this )
class DB {
protected $_conn;
public function __construct( $user, $pass, $database='NPD', $host='localhost' ){
try{
$this->_conn = new PDO("mysql:host={$host};dbname={$database}" , $user , $pass);
echo "connected";
}catch(Exception $e){
echo $e->getMessage();
}
}
public function insertInto($tableName , $info){
$sql = 'INSERT INTO $tableName (';
$sql .= '`'implode('`,`', array_keys($info[0])).'`';
$sql .= ')VALUES';
foreach ($info as $index => $row) {
$sql .= '(';
foreach( $row as $column => $value){
$sql .= ':'.$column.$index.',';
$params[':'.$column.$index] = $value;
}
$sql = rtrim($sql, ',');
$sql .= '),';
}
$sql = rtrim($sql, ',');
$stmt = $this->_conn->prepare($sql);
$stmt->execute($params);
}
}
}
$da = new DB('root', '');
$da->insertInto('tableOne',array( array('name' => 'lolo' , 'deg' => '100') ) );
First of all you loose any sql injection protection on the column names. If you can manage the placeholders on the values, then that is ok, but without using them there you loose protection on that as well. This can be solved by using the db schema itself, via Show columns but that gets a wee bit complex.
https://dev.mysql.com/doc/refman/5.7/en/show-columns.html
Second, your input array structure is all wrong, it needs to be array(0=>array(...), 1=>array(...)) instead of just array(...)
Third I would make this class a "Singleton" but that's just me
http://coderoncode.com/design-patterns/programming/php/development/2014/01/27/design-patterns-php-singletons.html
Forth, if you just want to do a single row at a time you can change this method
public function insertInto($tableName , $info){
$sql = 'INSERT INTO $tableName (';
$sql .= '`'implode('`,`', array_keys($info)).'`';
$sql .= ')VALUES(';
$params = array();
foreach( $info as $column => $value){
$sql .= ':'.$column.$index.',';
$params[':'.$column.$index] = $value;
}
$sql = rtrim($sql, ',');
$sql .= ')';
$stmt = $this->_conn->prepare($sql);
$stmt->execute($params);
}
And use the current input array structure you have.
This Is how i coded my own insert function
public function insertRecord($table,$records){
//A variable to store all the placeholders for my PDO INSERT values.
$placeholder = '';
for ($i = 0; $i < sizeof($records); $i++){
$placeholder[$i] = '?';
}
//A FOR-LOOP to loop through the records in the $record array
$placeholder = implode(',', $placeholder);
//Imploding ',' in between the placeholders
$sql = "INSERT INTO ".$table." VALUES ("{$placeholder}")";
$query = $this->dbh->prepare($sql);
$query->execute($records);
}
It Might not be the best..worked for me though.
As some other answers/comments have stated, there are quite a few critiques one could make about this overall process. However, in the interests of simply answering the question, you may want to just build the statement by looping through the columns, then looping through the values, then executing the finished statement (code below is just an example and hasn't been tested):
require 'connect.php';
class DB {
public function insertInto($tableName , $info){
global $db;
$query = "INSERT INTO $tableName (";
$columns = array_keys($info);
// build the columns in the statement
$length = count($columns);
foreach($columns as $index => $column) {
$query .= "$column";
if ($index+1 < $length) {
$query .= ','
}
}
$query .= ") VALUES ("
// build the values in the statement
$i = 1;
$length = count($info);
foreach($info as $value) {
$query .= "'$value'"
if ($i < $length) {
$query .= ","
}
$i++;
}
$query .= ")"
$stmt = $db->prepare($query);
$stmt->execute();
}
}
$da = new DB;
$da->insertInto('tableOne',array('name' => 'lolo' , 'deg' => '100'));
I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.