mysql query data insertion through php - php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$value1=$_POST['txtname'];
$value2=$_POST['cellnumber'];
$value3=$_POST['dist'];
$value4=$_POST['specialization'];
$value5=$_POST['membername'];
$value6=$_POST['date'];
$sql = "INSERT INTO students (StudentName, CellNumber, District, Specialization, PromotionMember, Date)
VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
if (!mysqli_query($sql)) {
die ('Error: ' . mysql_error());
}
else
{
echo ("معلومات ارایه شده شما ثبت شد");
header("Location: register.html");
}
mysqli_close();
?>
connection is successfull but data insertion is getting error on line 23 which is (if (!mysqli_query($sql)) { )
enter image description here

Your query doesn't run because you are using the MySQLi function wich need 2 parameters to execute your query.
So instead of
mysqli_query($sql)
you have to do:
mysqli_query($conn, $sql)
Your code also looks vulnerable to SQL Injections, so you want to know how to escape the strings in MySQLi. I recommend you to use prepared statements.
I hope this will help!

Try this code...
$sql = "INSERT INTO students (StudentName,CellNumber, District, Specialization, PromotionMember, Date)VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$q=mysqli_query($conn,$sql);
if (!$q) {
die ('Error: ' . mysqli_error($conn));
}else{header("Location: register.html");}

Try This code..
$sql = "INSERT INTO students (StudentName, CellNumber, District, Specialization, PromotionMember, Date)
VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$qw=mysqli_query($conn,$sql);
if($qw)
{
header("Location: register.html");
}

Related

Why does the following not appear to open an SQL connection?

I find that the folowing script hangs for some reason. It will load and PHP doesn't see any errors, but it will not process the data (noting that we are in a context where I have a seperate login database open.)
In process.php we have the following:
<? PHP
//Process the POST data in prepration to write to SQL database.
$_POST['chat_input'] = $input;
$time = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$name = $_SESSION['username'];
$servername = "localhost";
$username = "id3263427_chat_user";
$password = "Itudmenif1!Itudmenif1!";
$dbname = "id3263427_chat_user";
$id = "NULL";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = 'INSERT INTO `chat` (`id`, `username`, `ip`, `timestamp`,
`message`) VALUES ('$id','$name', '$ip', '$time', '$input')';
if(mysqli_query($link, $sql)){
mysqli_close($conn);
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
the html form passed to the script above is as follows:
<form action="/process.php" method="post" id="chat">
<b> Send A Message (500 Character Max):</b><br>
<textarea name="chat_input" form="chat" size="500"></textarea>
<input type="submit" value=submit>
</form>
Not sure what's going on with this.
You got the syntax error because you're closing the $sql string before $id with your '.
What is this about your $id variable? With your current code you will insert the String "NULL". If you want to set the sql value null you should use $id = null; or just don't insert any value.
If you want your database to set an id, also leave it blank.
$input = $_POST['chat_input'];
$id = null;
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
First solution
If this isn't a production code, you could insert the variables directly into the statement, but you should use " instead of ' for your sql string, so you can insert variables and ' without closing the string.
$sql = "INSERT INTO chat (id, username, ip, timestamp, message) VALUES ('$id', '$name', '$ip', '$time', '$input')";
if($conn->query($sql) === true) {
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $sql. " .$conn->error;
$conn->close();
}
Second solution
A better approach would be a prepared statement.
$stmt = $conn->prepare('INSERT INTO chat (username, ip, timestamp, message) VALUES (?, ?, ?, ?)');
$stmt->bind_param("ssss", $username, $ip, $time, $input);
if($stmt->execute()) {
$stmt->close();
$conn->close();
header('Location: ../protected_page.php');
} else {
echo "ERROR: Could not able to execute $stmt. " . $conn->error;
$stmt->close();
$conn->close();
}
The "s" in bind_param() defines a string at the given position, if you want to insert an integer, use "i" instead.
e.g. bindParam("sis", $string, $integer, $string);

form submitted data is not saved into phpmyadmin

I am using the below php code in my localhost on apache server, it shows no error and everything seems going fine when I submitted data in html form but the data is not saved in phpmyadmin table. Anyone can help?
<?php
$servername = 'localhost';
$username = 'root';
$password = 'xxxx';
$database = 'newtable';
$con = mysqli_connect("$servername","$username","$password","$database");
if (! $con){
die('Could not connect: ' . mysqli_error());
}
$sql = "INSERT INTO newtable (firstname, lastname) VALUES ('$_POST[firstname]', '$_POST[lastname]')";
if (! $sql)
{
die('Error: ' . mysqli_error());
}
echo "Record Added Successfully!";
mysqli_close($con);
?>
and html code is:
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" /><br><br>
Lastname: <input type="text" name="lastname" /><br><br>
<input type="submit" />
</form>
</body>
</html>
You forgot to execute your query and please use prepared statement like below
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO newtable (firstname, lastname) VALUES (?, ?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $firstname, $lastname);
$stmt->execute();
You didn't execute your insert query statement anywhere, so the data was not added.
Replace below line:
if (! $sql)
{
die('Error: ' . mysqli_error());
}
with
if ($mysqli->query($con, $sql) !== TRUE)
{
die('Error: ' . mysqli_error($con));
}
You just write your query forget to execute it
$sql = "INSERT INTO newtable (firstname, lastname) VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."')";
$result=mysqli_query($con,$sql);// execute it
if (! $result)
{
die('Error: ' . mysqli_error($con));// need to pass connection as parameter
}
read
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.query.php
Better to use bind statement to prevent form sql injection
$sql = "INSERT INTO newtable (firstname, lastname) VALUES (?, ?)";
$stmt = $con->prepare($sql);
$stmt->bind_param("ss", $firstname, $lastname);
$stmt->execute();
Thank you guys for you answers, It worked
all I needed to add $result=mysqli_query($con,$sql);
is it a execution of the program?
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$database = 'newtable'; $con = mysqli_connect("$servername","$username","$password","$database");
if (! $con){ die('Could not connect: ' . mysqli_error()); }
$sql = "INSERT INTO yourTableName (firstname, lastname) VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."')";
if (! $sql) { die('Error: ' . mysqli_error()); } echo "Record Added Successfully!"; mysqli_close($con);
?>
If you are using local host then the db password is blank by default and you need to give your table name in the insert query.

Php and Mysql communication [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
i've Apach2, Mysql and php (also php-mysql); i'm trying to insert from a form (varchar, varchar, password, date, varchar)into the table utenti in my db music:
Describe Utenti
I'm using procedural style mysqli: It says me "Insert success" but it doesn't write for real on the Db;
<?php
$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$password = $_POST['password'];
$datanascita = $_POST['datanascita'];
$email = $_POST['email'];
$host = "localhost";
$user = "root";
$password = "popolo";
$dbname = "music";
//Connessione
$con = mysqli_connect($host, $user, $password, $dbname);
//verifica eventuali errori
if (mysqli_connect_errno()) {
echo "Connesione fallita" . mysqli_connect_error();
exit();
} else {
echo "Connected \n";
//Inserting record in table using INSERT query
$mysqli = "INSERT INTO Utenti (`nome`, `cognome`, `password`, `datanascita`, `email`)
VALUES ($nome, $cognome, $password, $datanascita, $email)";
mysqli_query($conn, $mysqli);
echo "Insert success";
}
mysqli_close($conn);
?>
whatever your query succeeded or not this message echo "Insert success"; will output, you should check if your query succeeded first , you must your varchar in 2 '
$mysqli = "INSERT INTO Utenti (`nome`, `cognome`, `password`, `datanascita`, `email`)
VALUES ('$nome', '$cognome','$password', '$datanascita', '$email')";
you can check like this:
$result = mysqli_query($conn,$mysqli);
if($result){
echo "Insert success";
} else {
echo "Insert failed, Error: ".$mysqli->error;
}

Mysql insert not working and not giving errors

i do not know why the following code will not work for inserting data into mysql.
if (!$link = mysql_connect('server', 'user', 'password')) {
echo '700';
exit;
}
if (!mysql_select_db('vendors', $link)) {
echo '701';
exit;
}
$sql2 = "INSERT INTO transactions (TransID, payment_status, last_name, first_name, payer_email, address_name, address_state, address_zip, address_country, verify_sign, payment_gross, ipn_track_id, business, reciver_email) VALUES ('kris', 'kris', 'kris', 'kris', 'kris','kris', 'kris', 'kris', 'kris', 'kris', 'kris', 'kris', 'kris', 'kris')";
$result2 = mysql_query($sql2, $link);
What is wrong with the code?
php is giving no errors.
Please try not to use mysql_connect instead use mysqli_connect or PDO_MySQL read this
Also use die to find if there is any errors in your code
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
Otherwise(recommended way)-
Procedural style
$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 Persons (firstname, lastname, email)
VALUES ('Happy', 'John', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
echo "New Person created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
MySQLi Object-oriented style
$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 Persons (firstname, lastname, email)
VALUES ('Happy', 'John', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New Person created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Try changing this
$result2 = mysql_query($sql2, $link);
Into this
$result2 = mysql_query($sql2, $link)or die(mysql_error());
You have to write the code like below to get the errors in your code
$result = mysql_query($sql2,$link) or die(mysql_error());
this or die(mysql_error()) will give you errors in query

Insertion In php not working

I have this php script that inserts data from a form into the database.The code always returns an error. What might be the problem.
NB: the names of the fields in the form are correctly matched.
<?php
$db_hostname = 'localhost';
$db_database = 'townmanagement';
$db_username = 'root';
$db_password = '';
// Connect to server.
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
// Get values from form
$fname= mysql_escape_string(trim ($_POST['fname']));
$lastname= mysql_escape_string(trim ($_POST['lname']));
$dpt=mysql_escape_string(trim($_POST['dpt']));
$user= mysql_escape_string(trim ($_POST['username']));
$psswd=mysql_escape_string(trim ($_POST['password']));
// Insert data into mysql
$sql="INSERT INTO staff_reg (fname, lname, dpt, username, password, registration_date)
VALUES ($fname, $lastname, $dpt, $user, SHA1($password), NOW())";
$result = mysql_query($sql);
if($result){
echo ("sUCCESSFUL");
}
else {
echo "error";;
}
?>
<?php
// close connection
mysql_close();
?>
You need to quote your parameters in the SQL statement
$sql="INSERT INTO staff_reg (fname, lname, dpt, username, password, registration_date)
VALUES ('$fname', '$lastname', '$dpt', '$user', SHA1('$password'), NOW())";
And if possible you should upgrade to mysqli or pdo.
You are missing quotes around your values:
$sql="INSERT INTO staff_reg (fname, lname, dpt, username, password, registration_date)
VALUES ('$fname', '$lastname', '$dpt', '$user', SHA1($password), NOW())";
For better troubleshooting, consider adding to your mysql_query statement to detect when and why the query fails:
$result = mysql_query($sql) or die( mysql_error() );
Finally, be aware that the mysql_* functions are deprecated. Please consider updating your code to use mysqli or PDO.
mysql_select_db($db_database,$db_server)
or die("Unable to select database: " . mysql_error());
//you have to select db using connection previously established
Try this: You should know, that I am not encouraging you to use mysql_ since it is deprecated, and you should learn and implement PDO in the future:
<?php
$db_hostname = 'localhost';
$db_database = 'townmanagement';
$db_username = 'root';
$db_password = '';
// Connect to server.
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
// Get values from form
$fname= mysql_escape_string(trim ($_POST['fname']));
$lastname= mysql_escape_string(trim ($_POST['lname']));
$dpt=mysql_escape_string(trim($_POST['dpt']));
$user= mysql_escape_string(trim ($_POST['username']));
$psswd=mysql_escape_string(trim ($_POST['password']));
$psswd2 = SHA1($psswd);
// Insert data into mysql
$sql="INSERT INTO staff_reg (fname, lname, dpt, username, password, registration_date)
VALUES ('".$fname."', '".$lastname."', '".$dpt."', '".$user."', '".$psswd2."', "NOW()" )";
if(mysql_query($sql)); {
echo ("sUCCESSFUL");
}else {
echo "error";;
}
mysql_close();
?>

Categories