i am trying to insert to a table and get the ID of the new row.
$mysqli = new mysqli("localhost", "dbuser", "dbpass", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO table (tbl1,tbl2,tbl3,tbl4,tbl5) VALUES ('".$tbll."','".$tbl2."','".$tbl3."','0.00','".$tbl5."'";
$mysqli->query($query);
$id_log = $mysqli->insert_id;
id_log is returning 0 no error anywhere in logs
on same file i am doing SELECT & UPDATE and all work perfectly
You missed a parenthesis here...
$query = "INSERT INTO table (tbl1,tbl2,tbl3,tbl4,tbl5) VALUES ('".$tbll."','".$tbl2."','".$tbl3."','0.00','".$tbl5."')";
----------------------------------------------------------^
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 have a form that posts variables back from a drop down list in php. I then need to take those values and update my database values for each "TeamName". I am using the following code but nothing is updating.
$g1 = mysql_real_escape_string($_POST['g1']);
$conn = mysql_connect("****.com","****","*****") or die("Connection to MYSQL");
mysql_select_db("****_teamlist", $conn) or die("Connection to MYSQL database failed");
$sSQL = "UPDATE Sheet1 Set g1='$g1' WHERE TeamName = 'TeamName' ";
$result = mysql_query($sSQL, $conn) or die(mysql_error());
Where is my error? I am stuck.
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...
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.