I am using mysqli class at one of my project, i want yours help with following...
How to insert custom insert query
like we do in mysql
INSERT INTO payment_slip VALUES(NULL, md5(code), 'ABC', 'tester', NOW());
How to get last insert id using this class.
Providing methods would be great help, thanks.
Just like the plain old mysql functions mysqli has a field for this too:
mysqli->insert_id
From php docs (note that this only demonstrates getting the ID, the parameters are hardcoded into the query):
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO payment_slip VALUES(NULL, md5(code), 'ABC', 'tester', NOW())";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
Running mysqli_insert_id() will also work, but you should use it like vbence said.
Related
I am a novice in PHP. I am trying to insert a variable's value into a MariaDB table and was trying to use mysqli_real_escape_string to escape '$value'.
I got the idea from here.
It inserted an empty string to the table(I did add a connection link to the database).
So, I copied and pasted the following code from PHP Manual, it still didn't work. The output I got was an error code alone: Error: 42000. What am I missing?
I am using a Virtualbox,
OS: CentOS7
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", mysqli_sqlstate($link));
}
$city = mysqli_real_escape_string($link, $city);
/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}
mysqli_close($link);
?>
Update: Thank you for your prompt response! I tried #Pilan's code but I was not able to insert a row. I created a table in the database called 'City'. I checked whether there was a database connection in the code and it did return "Connected". Here is the updated code:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else {
echo "Connected";
$city = "'s Hertogenbosch";
// Connect to db, returns mysqli-connection
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// Prepare, "?" for placeholders, returns mysqli-statement
$stmt = $mysqli->prepare("INSERT INTO City (Name) VALUES (?)");
// Bin param to statement, with type "s" for string
$stmt->bind_param("s", $city);
//Execute
/* this query with escaped $city will work */
if ($stmt->execute()) {
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}
}
mysqli_close($link);
?>
Update: Thanks guys, The code worked, It did insert into the table but 'Row inserted' didn't show up: turns out, I forgot to take out the semicolon from 'execute()' inside if conditional statement.
Here you got an example of a prepared statement:
$city = "'s Hertogenbosch";
// Connect to db, returns mysqli-connection
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// Prepare, "?" for placeholders, returns mysqli-statement
$stmt = $mysqli->prepare("INSERT INTO myCity (Name) VALUES (?)");
// Bin param to statement, with type "s" for string
$stmt->bind_param("s", $city);
// Well execute :D
$stmt->execute();
For details have a look here: prepare, bind
I have a form with an array of something like this:
Address[addr1], address[addr2], address[pin] etc..
How can I insert and retrieve this into database? anyhelp will be greatly appreciated.
<pre><input placeholder="Street Address" type="text" name="address[addr1]" /><span class="icon-place"></span></span></pre>
Don't forget to validate your input fields to prevent sql injection.
But below should put you on the right track. I edited my answer. try this.
<?
$lineOne = $_POST['address[addr1]'];
$lineTwo = $_POST['address[addr2]'];
$pin = $_POST['address[pin]'];
//form sql statement
$sqlSet = "INSERT INTO addressTable(address1, address2, pin)
VALUES('$lineOne', '$lineTwo', '$pin')";
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// execute insert query
$insertQuery = mysqli_query($con, $sqlSet);
//form sql statement
$sqlGet = "SELECT * FROM addressTable";
// execute select query
$selectQuery = mysqli_query($con, $sqlGet);
?>
<?php
$address1=$_POST['Address'][addr1];
$address2=$_POST['Address'][addr2];
$pin=$_POST['Address'][pin];
$query=mysqli_query($link, "insert into your_table(address1, address2, pin) values('$address1', '$address2', '$pin')";
try this process
For Insertion:
Method 1 : use json_encode($address) and save data. See detail
Method 2 : try foreach() then insert data like
foreach($address as $a){
//query for insertion
}
For Retrieve data:
For Method 1 : use json_decode() to decode all json data. See detail
Method 2 : normal process how you retrieve data
foreach($address as $a){
//query for insertion
}
When using data from users it's pretty important to prepare statements rather than just putting them into building the SQL query as a string to avoid injection attacks.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO addr_table (addr1, addr2, pin) VALUES (?, ?, ?)")) {
/* bind parameters for markers */
$stmt->bind_param("sss", $addr1, $addr2, $pin);
$address1=$_POST['Address']['addr1'];
$address2=$_POST['Address']['addr2'];
$pin=$_POST['Address']['pin'];
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
(Some of the close business isn't as necessary, but is there for completeness.)
In my mysql table i have an id-column which is set to autoincrement.
then i do queries like this:
INSERT INTO table (id, foo) VALUES ('', 'bar')
how can i then safely find out which id was generated with this insert?
if i just query the last id this might not be safe, since another insert could have happened in the meantime, right?
There's a PHP and also a MySQL function for this: mysqli_insert_id() and PDO::lastInsertId().
http://php.net/manual/en/function.mysql-insert-id.php
Use LAST_INSERT_ID() in SQL
SELECT LAST_INSERT_ID();
Use mysql_insert_id() in PHP
If you are using PHP to get the auto_incremented value that is returned after an INSERT statement, try using the MySQLi insert_id function. The older mysql_insert_id() version is being deprecated in PHP.
An example below:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
http://php.net/manual/en/function.mysql-insert-id.php
If you use mysql_query("..."), then mysql_insert_id() is the function you need. If you use something else to do queries, then the corresponding documentation should be checked
Be Careful when using mysql_insert_id() specially if you have multiple connections to the Database. Because It doesn't get the value of the query you've inserted. it gets the latest id of the table. It may be a row another query has inserted. Only use this function if you access Database in one connection.
https://www.php.net/manual/en/function.mysql-insert-id.php
Since it's PHP, mysql_insert_id should do the trick
Take a look at the rather good example at http://php.net/manual/en/function.mysql-insert-id.php
mysqli_insert_id();
You can also simply run this query:
INSERT INTO table (foo) VALUES ('bar')
Simple method
Insert data :
$sql = "INSERT INTO table (id, foo) VALUES ('', 'bar')";
$conn->query($sql)
Get ID :
return $conn->insert_id;
also in PDO after the execute command as the example below:
$lastId = $dbh->lastInsertId();
click for REF
I'd like to know if there is a simple way to fetch data from mysql tables with "correct" data types? What i mean, if field type is for example INT or SMALLINT is it possible to pass those types directly to PHP as integers?
I did some searching and found mysqli_fetch_fields, but for SMALLIT type is 2, for INT 3 and so on. It could be done that way, but it looks rather clumsy workaround. Is there any better way?
I'm using PHP and mysqli.
Thank you.
The most straightforward way is to build your own database handler on top of the mysqli calls that does that for you.
http://www.php.net/manual/en/mysqli-result.fetch-field-direct.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = $result->fetch_field_direct(1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>
You can use this code
SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'yourtablename replace your table name' AND COLUMN_NAME = 'tablecolumnname replace your table column name';
Use this before run your main query and after when you get your datatype then execute your operation.
How can I return a declared string like ( lastInsertId ) from my MySQL stored procedure and out? It's really annoying I can't return error messegts, complate messages and more out to my code in PHP5.
I hope somebody can help me here, I have search Google around without luck :(
Thanks to everybody.
The function you need is mysqli->insert_id
This is the example that php.net provides, I think this function is what you are looking for:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
You'll find more info here: php.net: mysqli->inert_id - Manual
If you need more help using it I'll be happy to help you.