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.
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.)
I'm trying to understand how the temporary tables work. But even when I copy and paste it from my tutorials, I don't get the expected result.
See the code underneath for more info.
At the moment the .php file returns a blank page (no errors),
while i would expect it to be:
1 Row inserted.
I looked for the error code but found out that temporary tables don't have an error code.
Does someone know what I'm doing wrong?
<?php
$link = mysqli_connect("localhost","xxx","xxx","xxx");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity (Name CHAR(30)");
$city = "'s Hertogenbosch";
$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);
?>
Looks like you have an error in your sql creation. You are missing a closing parenthesis: ")"
CREATE TEMPORARY TABLE myCity (Name CHAR(30)
Adrien.
this works for me
<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
$mysqli = new mysqli("localhost", "root", "admin123", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TEMPORARY TABLE CITIES (
id int(11) NOT NULL,
name varchar(64) NOT NULL
)");
//$mysqli->autocommit(FALSE);
$mysqli->query("INSERT INTO CITIES VALUES ('1', 'Bavaria')");
$mysqli->query("INSERT INTO CITIES VALUES ('2', 'Havana')");
//$mysqli->commit();
if ($result = $mysqli->query("SELECT * FROM CITIES LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
//$mysqli->query("DROP TABLE CITIES");
$mysqli->close();
Remember Temporary tables only exist by session, sometimes we need create conventional table and truncate later...
You would must think use DB lib like Doctrine DBAL or ADODb or something like that...
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.
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.