PDO prepared statement with insertion in database - mysql

Please i have this quetion,
I have here:
$query = $db->prepare('Update survey_content set '.$type.' = '.$type.'+1 where id = '.$where);
$query->execute();
I'm new to PDO and i really don't know how to create a new query, i need to add a record on the database, is it ok like this?
$query1 = $db->prepare('INSERT INTO daily (selected)
VALUES (.$type.)');
$query1->execute();

Use a placeholder and fill the value in the execute method
$query1 = $db->prepare("INSERT INTO daily (selected)
VALUES (?)");
$query1->execute($selected_data);
or bind the parameter seperately
$query1 = $db->prepare("INSERT INTO daily (selected)
VALUES (:sel_dat)");
$query1->bindParam(":sel_dat",$selected_data);
$query1->execute();

Related

Insert all in mysql [duplicate]

Assuming that I have two tables, names and phones,
and I want to insert data from some input to the tables, in one query. How can it be done?
You can't. However, you CAN use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;
http://dev.mysql.com/doc/refman/5.1/en/commit.html
MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)
Old question, but in case someone finds it useful... In Posgresql, MariaDB and probably MySQL 8+ you might achieve the same thing without transactions using WITH statement.
WITH names_inserted AS (
INSERT INTO names ('John Doe') RETURNING *
), phones_inserted AS (
INSERT INTO phones (id_name, phone) (
SELECT names_inserted.id, '123-123-123' as phone
) RETURNING *
) SELECT * FROM names_inserted
LEFT JOIN phones_inserted
ON
phones_inserted.id_name=names_inserted.id
This technique doesn't have much advantages in comparison with transactions in this case, but as an option... or if your system doesn't support transactions for some reason...
P.S. I know this is a Postgresql example, but it looks like MariaDB have complete support of this kind of queries. And in MySQL I suppose you may just use LAST_INSERT_ID() instead of RETURNING * and some minor adjustments.
I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
my way is simple...handle one query at time,
procedural programming
works just perfect
//insert data
$insertQuery = "INSERT INTO drivers (fname, sname) VALUES ('$fname','$sname')";
//save using msqli_query
$save = mysqli_query($conn, $insertQuery);
//check if saved successfully
if (isset($save)){
//save second mysqli_query
$insertQuery2 = "INSERT INTO users (username, email, password) VALUES ('$username', '$email','$password')";
$save2 = mysqli_query($conn, $insertQuery2);
//check if second save is successfully
if (isset($save2)){
//save third mysqli_query
$insertQuery3 = "INSERT INTO vehicles (v_reg, v_make, v_capacity) VALUES('$v_reg','$v_make','$v_capacity')";
$save3 = mysqli_query($conn, $insertQuery3);
//redirect if all insert queries are successful.
header("location:login.php");
}
}else{
echo "Oopsy! An Error Occured.";
}
Multiple SQL statements must be executed with the mysqli_multi_query() function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

get the last id of the query with pdo php [duplicate]

I have a query, and I want to get the last ID inserted. The field ID is the primary key and auto incrementing.
I know that I have to use this statement:
LAST_INSERT_ID()
That statement works with a query like this:
$query = "INSERT INTO `cell-place` (ID) VALUES (LAST_INSERT_ID())";
But if I want to get the ID using this statement:
$ID = LAST_INSERT_ID();
I get this error:
Fatal error: Call to undefined function LAST_INSERT_ID()
What am I doing wrong?
That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().
Like:
$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();
If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:
$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).
Like this $lid = $conn->lastInsertId();
Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

How to INSERT an entry without content into a table in ZF2?

In my database there is a table, that contains only one row: id. It's something like a facade for another table:
Now I want to add an entry into whatever_set, in order to be able to create entries in the dependent tables. In SQL I would write:
INSERT INTO whatever_set VALUES ();
But when I try it with Zend\Db
$action = new Insert(whatever_set');
$data = [];
$action->values($data);
$sql = new Sql($this->dbAdapter);
$statement = $sql->prepareStatementForSqlObject($action);
$result = $statement->execute();
I get an exception:
values or select should be present
There are some possible workarounds (see below). But is there though a "Zend way" to save empty with no VALUES? How to do this?
Workaround 1
Custom Insert class.
Workaround 2
Raw SQL like
$sql = 'INSERT INTO whatever_set VALUES ();';
$result = $this->dbAdapter->getDriver()->getConnection()->execute($sql);

mysql: get affected row record after update

I recently use two sql queries to get row record after update like this, for example:
Step 1: I update point for user test#gmail.com
$sql = "UPDATE user SET point=point-:point WHERE email=:email";
$result = $conn->prepare($sql);
$result->bindValue(':point', 2);
$result->bindValue(':email', 'test#gmail.com');
$result->execute();
Step 2: I have to use another sql query to get row['point'] after it is updated
$sql = "SELECT point FROM user WHERE email=:email";
$result = $conn->prepare($sql);
$result->bindValue(':email', 'test#gmail.com');
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
echo $row['point'];
So, my question is, is ther a shortcut for this? such as 1 single query to achieve this?
Many thanks

Update database using mySQL & php PDO

I've created a database for one of my classes simulating a hotel reservation form.
my database table name that I am trying to get values from is tblNameRes and the fields are fldName and pkEmail
I have gotten the values from the database and displayed them in this table here:
http://www.uvm.edu/~cchessia/cs148/assign4/strugg.php
I want to add a column to be able to update and delete these records, but I don't really understand how. I have this code:
$updating = $db->prepare('UPDATE `tblNameRes` SET `name` = `name` + ? WHERE `id` = ?');
$updating->execute(array(20, $id));
but I want to be able to click a link that says "update" and it will take me to another page that allows me to edit the data and submit it back to the database. I would also like to be able to delete the data in the same way.
I'm a little confused to what you would like, would you like the PDO code to both update and delete items from your DB? If so I use this, I'm also new to PDO. Also try not to use ' around table/field names.
/** Code to update */
$query = "UPDATE tblNameRes SET name ='$name' WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->BindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
/** Code to delete */
$query = "DELETE FROM tblNameRes WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->BindValue(':id', $id, PDO::PARAM_INT);
$query->execute();
Let me know if this helps, or is not what you wanted. I'm new here so I can't post 'comments'.
/* code for update and remove this 'at the beginning an at the end*/
$query = "UPDATE tblNameRes SET name =:fname WHERE id = :id";
$stmt = $db->prepare($query);
$stmt->BindValue('fname',$fname);
$stmt->execute();