Insertion In php not working - php

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();
?>

Related

mysql query data insertion through 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");
}

Query Fails whenever I want to insert

Each time i submit a form through the code below, i get "Query failed" but i can't seems to find the error.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'order (pass, phone, fname, lname)
VALUES('test#yahoo.com','060606060606','James'' at line 1
Please someone help me.
<?php
//Start session
session_start();
//Include database connection details
require_once('../db/config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$pass = clean($_POST['pass']);
$phone = clean($_POST['phone']);
$fname = clean($_POST['fname']);
$lname = clean($_POST['lname']);
//Create INSERT query
$qry = "INSERT INTO order (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: success.php");
exit();
}else {
die("Query failed");
}
?>
I also tried to check if the user inputs are empty and it was okay but it doesn't insert.
The name 'order' is a MySQL reserved keyword.
Use backtick to enclose table name,
$qry = "INSERT INTO `order` (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
^ enlcose table name with backtick
Backtick
And use "mysqli"
$qry = "INSERT INTO `order` (pass, phone, fname, lname) VALUES('$pass','$phone','$fname','$lname')";
$result = mysqli_query($conn,$qry);

I cannot insert data into database

I have checked all table and column names are right and there are no mistakes in any input names but it is not inserting that data.
<?php
if(isset($_POST['Murad'])){
session_start();
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$userName=$_POST['username'];
$password=$_POST['pwd1'];
$userName = stripslashes($userName);
$password = stripslashes($password);
$email=$_POST['email'];
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "123";
$mysql_databse = "websiteusersa";
$bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysqli_select_db($bd,'websiteusersa');
$sql = "INSERT INTO websiteusersa
(fullname,lastname,userName,email,pass)
VALUES ( '$firstname', '$lastname','$userName', '$email','$password')";
$query = mysqli_query($bd, $sql);
header("location: main.php?/$firstname/");
}
?>
You can post a question here but not check for error messages?
$query = mysqli_query($bd, $sql) or die(mysqli_error($db));
^
Its a simple debugging process which others have to perform for you then. That will simply tell you where the error is.
Check your statement here:
$sql = "INSERT INTO websiteusersa
(fullname,lastname,userName,email,pass)
VALUES ( '$firstname', '$lastname','$userName', '$email','$password')";
maybe the column fullname could possibly mean firstname that's why your code doesn't work.

Mysql insertion failing in script

I have been breaking my head against this and still I am unable to understand that why wouldn't this work
include ("db_conn.php");
//function for sanitizing the user input
function clean_input($data)
{
$data = stripslashes($data);
$data = trim($data);
$data = htmlspecialchars($data);
return $data;
}
//registration form data validation
if(!empty($_POST['s_register_submit']))
{
$Salutation= $F_Name= $L_Name= $email= $pass= $P_Number = "";
$Salutation= clean_input($_POST['Salutation']);
$F_Name= clean_input($_POST['F_Name']);
$L_Name= clean_input($_POST['L_Name']);
$email= clean_input($_POST['email']);
$pass= clean_input($_POST['pass']);
$P_Number= clean_input($_POST['P_Number']);
$query= "INSERT INTO STUDENT (Salutation, F_Name, L_Name, email, password, phone)
VALUES
(`$Salutation`,`$F_Name`,`$L_Name`,`$email`,`$pass`,`$P_Number`)";
$query1= mysqli_query($dbhandle,$query) || die("Unable to insert");
echo "Saved";
And here are the contents for db_conn.php
$user="root";
$password="";
$host="localhost";
$dbname="Interns";
$dbhandle=mysqli_connect($host, $user, $password, $dbname);
if(!$dbhandle)
{
die("Unable to connect");
}
echo "Connected";
When running db_conn.php directly or through the script in which it is included, its echoing "Connected", still the query returns "Unable to Insert".
You wrap strings in quotes, not ticks. Ticks are reserved for identifiers.
$query= "INSERT INTO STUDENT (Salutation, F_Name, L_Name, email, password, phone)
VALUES
(`$Salutation`,`$F_Name`,`$L_Name`,`$email`,`$pass`,`$P_Number`)";
should be
$query= "INSERT INTO STUDENT (Salutation, F_Name, L_Name, email, password, phone)
VALUES
('$Salutation','$F_Name','$L_Name','$email','$pass','$P_Number')";

Insert form data in one table and then update an enum value in a different table?

I am using a code to insert a users form data into the database, that bit works fine. However, i also want to run another query and update an enum value 'form2_completed?' from No to Yes. I have added in the update query and now for some reason the script is not working and says 'ERROR'
Can someone please show me where i am going wrong. thanks
<?php
session_start();
$db_hostname = 'localhost';
$db_database = 'hewden1';
$db_username = 'root';
$db_password = '';
$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());
$cname = $_POST['cname'];
$creg = $_POST['creg'];
$address = $_POST['address'];
$post = $_POST['post'];
$contactn = $_POST['contactn'];
$contactt = $_POST['contactt'];
$email = $_POST['email'];
$vat = $_POST['vat'];
$ipaddress = $_SERVER["REMOTE_ADDR"];
$sql="INSERT INTO supplier_registration (company_name, company_reg_number, company_address, company_postcode, contact_name, contact_number, contact_email, company_vat_number, date_time, user_ip)
VALUES ('$cname', '$creg', '$address', '$post', '$contactn', '$contactt', '$email', '$vat', NOW(), '$ipaddress')";
$sql="UPDATE supplier_session SET form2_completed? = 'Yes' WHERE form2_completed? = 'No'";
$result = mysql_query($sql);
if($result){
$success = "<div class='success'></div>"; // use the $success
//encode the URL parameter as :
$success = urlencode($success);
header("Location: index.php?success=$success");
}else {
echo "ERROR";
}
?>
You are overwriting the variable $sql and not running INSERT. Try:
$sql="INSERT INTO supplier_registration (company_name, company_reg_number, company_address, company_postcode, contact_name, contact_number, contact_email, company_vat_number, date_time, user_ip)
VALUES ('$cname', '$creg', '$address', '$post', '$contactn', '$contactt', '$email', '$vat', NOW(), '$ipaddress')";
$result = mysql_query($sql);
$sql="UPDATE supplier_session SET form2_completed? = 'Yes' WHERE form2_completed? = 'No'";
$result = mysql_query($sql);
Please note that the method you have used is deprecated from php 5.5.0. so i suggest you consider mysqli or PDO. examples can be found in below php manual links
http://www.php.net/manual/en/mysqli.query.php
http://www.php.net/manual/en/pdo.query.php

Categories