Insert stored procedure in PHP - php

I have a simple insert statement to save form details in PHP.
I want to convert this into store procedure.
Below is my current code how
$servername = "localhost";
$username = "aaaaaa";
$password = "ppppp";
$dbname = "xxxx_database";
$sName = $_POST["name"];
$sEmail = $_POST["email"];
$sPhone = $_POST["Number"];
$sInterest = $_POST["interest"];
$Comments = $_POST["Inquiry"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ContactForm (Name, Email, PhoneNumber,Interest,Comments) VALUES ('$sName', '$sEmail', '$sPhone','$sInterest', '$Comments')";
if ($conn->query($sql) === TRUE) {
echo "New record created";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
And this is my Store procedure
CREATE DEFINER = `xxx`#`localhost` PROCEDURE `SpInsertContactForm` ( IN `Name` TEXT CHARSET armscii8, IN `Email` TEXT CHARSET armscii8, IN `PhoneNumber` TEXT CHARSET armscii8, IN `Interest` TEXT CHARSET armscii8, IN `Comments` TEXT CHARSET armscii8 ) NOT DETERMINISTIC NO SQL SQL SECURITY DEFINER INSERT INTO ContactForm( Name, Email, PhoneNumber, Interest, Comments )
VALUES (
Name, Email, PhoneNumber, Interest, Comments
)
How can i use this store procedure. I am new to php and mysql need pointer in this.
I use SP as
if (!$mysqli->query("CALL SpInsertContactForm($sName, $sEmail, $sPhone,$sInterest, $Comments)"))
{
echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
This doesn't save anything in DB

you cal use this: $mysqli->query("CALL SpInsertContactForm('<your_namevalue>','<your_emailvalue>','<your_phonevalue>','<your_interestvalue>','<your_commentvalue>')
For more please follow the link:
http://php.net/manual/en/mysqli.quickstart.stored-procedures.php

Related

INSERT TABLE using php variable

What is the correct syntax for the SQL INSERT INTO when using a php variable for table name. I have tried everything and it won't insert when I use php variable.
This is what I have so far. is this right?
$sql = "INSERT INTO ".$table." (`Name`) VALUES ('A')";
mysqli_query($conn, $sql);
if I switch $table to the actual table name, it works
$sql = "INSERT INTO 'myTable' ('Name') Values ('A')";
It works for me fine
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stack_over_flow";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
When Table Name is Variable
$DB_TBLName = "abc";
$sql_ac_valuee = "INSERT INTO $DB_TBLName (a, b ,c) VALUES "."('10','20','30')";
if ($con->query($sql_ac_valuee) === TRUE) {
}
else{
echo "Error: " . $sql_ac_valuee . "<br>" . $con->error;
}
When Use direct Table Name
$sql_ac_valuee = "INSERT INTO abc (a, b ,c) VALUES "."('10','20','30')";
if ($con->query($sql_ac_valuee) === TRUE) {
}
else{
echo "Error: " . $sql_ac_valuee . "<br>" . $con->error;
}
$query = "INSERT INTO $tname (place,dis,p_1,p_2,p_3,p_4,p_5,p_6) VALUES('$name','$discription','$bfile','$file1','$file2','$file3','$file4','$file5')";
$result =mysqli_query($link,$query);
if(!$result){echo mysqli_error($link);?>
This was my code and the output is:
Skardu.You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(place,dis,p_1,p_2,p_3,p_4,p_5,p_6) VALUES('Sundus','Few people can afford the T' at line 1
its work fine when i use skardu instead of varible

PHP & mySQL obtaining last insert ID

I'm quite new to this php/mysql deal and I'm having a hard time figuring out this situation particularily.
I have two tables, one of them is "dog" table and the other one is the "date" table. In order to insert a record in the "dog" table I MUST first insert a date in the "table" date and get the autoincrement id from that date.
Problem is that I've tried reading several posts on how to get the last insert id from a table you just inserted a record on and I can't seem to make it work.
$sql1="INSERT INTO FECHAS (fecha) VALUES (NOW())";
mysql_query($sql1);
echo $sql1;
$sql3="SELECT LAST_INSERT_ID()";
mysql_query($sql3);
echo $sql3;
$sql2="INSERT INTO PERRO (nombre_perro,FECHAS_id_fecha) VALUES ('$nombre_perro_var', '$last_id')";
echo $sql2;
if (!$mysqli->query($sql2)) {
echo 'Error: ', $mysqli->error;
}
$result2 = mysql_query($sql2);
Please forgive this code, I'm new and learning.
Thanks!
Use mysqli instead of mysql_
Connecting with mysqli:
$connection = mysqli_connect($hostname, $username, $password, $database_name);
Inserting into a table:
mysqli_query($connection, $sql);
Retrieving last inserted id:
$id = mysqli_insert_id($connection);
**Database**
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
**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 MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
***$last_id = $conn->insert_id;***
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
**Example (MySQLi Procedural)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
***$last_id = mysqli_insert_id($conn);***
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
**Example (PDO)**
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
***$last_id = $conn->lastInsertId();***
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
A procedural solution (although it might be slightly wrong - I'm terrible at PHP)...
<?php
include('path/to/connection/stateme.nts');
$query = "
INSERT INTO fecha (fecha) VALUES (NOW());
";
mysqli_query($db,$query);
$query = "
INSERT INTO perro (nombre_perro,id_fecha) VALUES (?,?);
";
$nombre_perro = 'rover';
$id_fecha = mysqli_insert_id($db);
$stmt = mysqli_prepare($db,$query);
mysqli_stmt_bind_param($stmt, 'si', $nombre_perro,$id_fecha);
mysqli_stmt_execute($stmt);
?>
You might consider binding both queries into a transaction, so that in the event that the second query fails for some reason, then the first query fails too.

Php to MySQL database

I have problem with MySQL database, I can't insert the information into the table. My php code seems to work, but when I run it nothing happens.
<?php
$servername = "localhost";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks";
$conn = new mysqli($servername, $fname, $lname,$klas,$file,$dbname);
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($servername, $fname, $lname,$klas,$file,)";
?>
You have three main problems in your code:
You're still not connected to the database
Only constructing and not executing
Having not matched parameters in the insert values
Solution :
1. Make a connection first
$conn = new mysqli($servername, $username, $password, $dbname);
The Parameter $servername, $username, $password, $dbname is obviously your hostname, Database Username, Password and the Database name
You should not have your table name or column names in the connection parameters
2. Construct the parameters which matches the coloumn name and variables correctly
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($fname, $lname,$klas,$file)";
3. Execute Your Query :
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note :
Also it's good practice to close your connection once you are done
$conn->close();
So, you should be having something like this
<?php
$servername = "localhost";
$username = "YourDBUsername";
$password = "YourDBPassword";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks"; //Hope you will have your db name here
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "
INSERT INTO student (fname, lname,klas,file) VALUES
('$fname'
,'$lname'
,'$klas'
,'$file');
";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Advice :
Always use prepared statements else clean your inputs before you insert.
Your connection should look something like this. link
<?php
//change the data into your connection data
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You made your query but didn't execute it.
if (mysqli_query($conn, $sql)) {
echo 'records created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($conn);
}

PHP / MySQL: How to return info if record already exists (without update)

I am using the below to insert a new row into a MySQL db.
The query for this is stored in a PHP file (ajax.php) and the input values are passed to this via an Ajax call in jQuery.
Everything works as intended but I would like to return a message to the user if an email is already in the db.
I know how to update a db row using ON DUPLICATE KEY but can someone tell me how I can just check for this and echo something if it exists there already (i.e. without updating it) ?
(email is a single primary key so I only need to check for this column.)
My PHP:
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"];
$sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
if ($conn->query($sql)){
echo 'DB Update successful';
}else{
echo 'DB Update failed';
}
$conn->close();
You just need a simple SELECT call before inserting.
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$email = $_POST["email"];
$dob = $_POST["dob"];
$sql = "SELECT email FROM Users WHERE email = " .$email;
$query = $conn->query($sql);
if (mysqli_num_rows($query) > 0){
echo "There exists an user with this email";
}
else {
$sql = "INSERT INTO Users (email, dob) VALUES ('" . $email . "', '" . $dob . "')";
if ($conn->query($sql)) {
echo 'DB Update successful';
}
else {
echo 'DB Update failed';
};
}
$conn->close();
The simple way is just to count the occurances of entries in the table with the same email as you are trying to store. Counting rather than SELECTing means it is quicker and only a count is returned not a complete row that you have to then look at or count the rows in the result.
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $Conn->prepare("Select Count(email) as cnt FROM Users WHERE email = ?");
$stmt->bind_param('s', $_POST["email"]);
$stmt->execute();
$stmt->bind_result($cnt)
$stmt->close();
if ( $Cnt > 0 ) {
// its already there so do whatever you want in this case
} else {
$sql = "INSERT INTO Users (email, dob) VALUES (?,?)";
$stmt = $Conn->prepare($sql);
$stmt->bind_param('ss', $_POST["email"],$_POST["dob"]);
if ($stmt->execute(){
echo 'DB Update successful';
}else{
echo 'DB Update failed';
}
}
$conn->close();

Simple insert into database doesn't work

I have a very simple bit of code to insert data into database.
It doesn't work. I do not get any error except cannot insert. I could connect to the database so that is not the issue.
The database has 3 fields, emailadd is the 2nd field. The other 2 are auto increment id and creation date, so also a field that on add, it will add current timestamp.
$inquiry = "INSERT INTO subscribe (emailadd) VALUES ('$myemail')";
$res = mysql_query($inquiry) or die("cannot insert");
$inquiry = "INSERT INTO `subscribe` (`emailadd`) VALUES ('$myemail')";
$res = mysql_query($inquiry,$con) or die('Not Inserted : ' . mysql_error());
Some time we need $con variable to identify the database connection, let see more check here
the mysql_query is deprecated, you need to use mysqli like so :
<?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 = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

Categories