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
Related
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 am very new to MySQl and I'm trying to check if an inputed email matches with any from my table. If it matches, I need to put the email and the other columns of the same row in another table.
What I get now is a blank row added to table2.
<?php
include "config.php";
$email = $_POST['email'];
$match = mysqli_query("SELECT email FROM table1 WHERE email = $email");
if($conn->query($match)){
//here i have to find the name, school, and grad_year that matches
// with the email from table 1 which is in the same row. I tried a couple of
//things but it didn't work. So i don't know what to put in there.
$insert = "INSERT INTO table2 VALUES(name,'$email',school,grad year )";
$conn->query($insert);
}
?>
Any help would be much appreciated!
Don't ever use the mysql* functions. They are deprecated and insecure. Use mysqli* or PDO instead. See below for sample code (I have NOT run it and there may be errors - the idea is to get you on the right road...)
<?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();
}
$email = $_POST['email'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE email=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $email);
/* execute query */
$stmt->execute();
/* bind result variables */
# NOTE: You may prefer $stmt->get_results() and $result->fetch_assoc()
# to this $stmt->bind_result() and $stmt->fetch().
$stmt->bind_result($name, $junk, $school, $grad_year);
/* fetch value */
if ($stmt->fetch()) {
$stmt2 = $mysqli->prepare("INSERT INTO table2 VALUES (?,?,?,?)");
$stmt2->bind_param("ssss", $name, $email, $school, $grad_year);
$stmt2->execute();
$stmt2->close();
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Or, if you don't care to know details along the way, this is a lot faster and simpler:
// yada,yada - get a conx
$email = $_POST['email'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO table2 SELECT * FROM table1 WHERE email=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $email);
/* execute query */
$stmt->execute();
/* the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function */
}
(SOURCE: Example copied from http://php.net/manual/en/mysqli.prepare.php and modified)
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."')";
----------------------------------------------------------^
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.
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.