Mysql insertion failing in script - php

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')";

Related

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

PHP is not inserting Data

I have run it on the local server and it worked perfectly, but when I uploaded it to my web hosting, it stopped working.
Basically when I submit the form the browser just keeps loading and when I check the database no data was inserted.
I checked my database connection and I was able to connect it but can't get data from it.
This is my php:
<?php
$servername = "localhost";
$username = "itclubac_root";
$password = "*******";
$dbname = "itclubac_itclub";
$tnp = 0;
$name = $_POST['name'];
$email = $_POST['email'];
$gender = $_POST['gender'];
$phone = $_POST['phone'];
$id = $_POST['id'];
$section = $_POST['section'];
$skills = $_POST['skills'];
$interests = $_POST['interests'];
$expectations = $_POST['expectations'];
$tnp = $_POST['tnp'];
$ip = $_SERVER['REMOTE_ADDR'];
if ( $tnp == 0 ) {
header('Location: ../../get_involved.php');
} else {
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$query = mysqli_query($con, "SELECT * FROM member_registration WHERE email = '".$email. "'");
if ( mysqli_num_rows($query) > 0 ) {
header('Location: ../../get_involved.php?status=exist');
} else {
$query = mysqli_query($con, "SELECT * FROM member_registration WHERE college_id = '".$id. "'");
if ( mysqli_num_rows( $query) > 0 ) {
header('Location: ../../get_involved.php?status=exist');
} else {
$sql = "INSERT INTO member_registration (name, email, gender, phone_no, college_id, section, skills, interests, expectations, ip_address) VALUES ('$name', '$email', '$gender', '+880$phone', '$id', '$section', '$skills', '$interests', '$expectations', '$ip')";
if ($con->query($sql) === TRUE) {
header('Location: ../../get_involved.php?status=success');
}
}
}
}
$con->close();
?>
Edit
This is the site: Form Pagehttp://itclub.acc.edu.bd/get_involved.php if you register here, the page will just keep loading. However if you try to access the registration.php directly it sends you to the form page page as I said it to. When I tested it on local, it worked perfectly but after uploading to the host this problem is occurring.
I tried to sort your code and maybe the error is related on the of your query,
$sql = "INSERT INTO member_registration (name, email, gender, phone_no, college_id, section, skills, interests, expectations, ip_address) VALUES ('$name', '$email', '$gender', '+880$phone', '$id', '$section', $'skills', '$interests', '$expectations', '$ip')";
Have you notice this part $'skills' of the line? change your code into,
$sql = "INSERT INTO member_registration (name, email, gender, phone_no, college_id, section, skills, interests, expectations, ip_address) VALUES ('$name', '$email', '$gender', '+880$phone', '$id', '$section', '$skills', '$interests', '$expectations', '$ip')";
maybe it help.

Why does my code not insert the details to the database?

I have written the following code to insert data into my database table, but unfortunately, it doesn't work. I have double and triple-checked the code and there are no errors at all. The console also doesn't show any as well.
I have not misspelled any of the details required to connect to the database and the variables are also correct so I am at a loss.
If anyone could help it would be be deeply appreciated.
My code:
<?php
function obfuscate($type, $data) {
if ($type == "PIN"):
$f_int = (int)md5($data);
$data = str_split($data);
$rev = implode("", array_reverse($data));
$sum = array_sum($data) + $f_int;
$data = implode("", $data);
$data += $sum + $rev + 1026;
// Keep the first four digits if the result is longer
if (strlen($data) > 4):
$data = substr($data, 0, 4);
endif;
return $data;
elseif ($type == "password"):
$data = password_hash($data, PASSWORD_DEFAULT, ['cost' => 12]);
return $data;
endif;
}
function insert_user($username, $email, $password, $PIN, $Account_Type, $Account_Status, $Referrer, $Balance) {
// Connect to the server and the database or show error
$connection = mysqli_connect("localhost", "root", "") or die("Couldn't connect to the server.");
mysqli_select_db($connection, "Calisoft_flu_db") or die("Couldn't connect to the database.");
// Sanitise the data
$username = mysqli_real_escape_string($connection, $username);
$email = mysqli_real_escape_string($connection, $email);
$password = mysqli_real_escape_string($connection, $password);
$PIN = mysqli_real_escape_string($connection, $PIN);
// Get the rest of the data
$Registration_Date = date("Y-m-d");
// Obfuscate password and PIN
$password = obfuscate("password", $password);
$PIN = obfuscate("PIN", $PIN);
// Make query and insert data to database
$query = "INSERT INTO `users` (`ID`, `Username`, `Email`, `Password`, `PIN`, `Registration_Date`, `Account_Type`, `Account_Status`, `Referrer`, `Balance`) VALUES ('NULL', '$username', '$email', '$password', '$PIN', '$Registration_Date', '$Account_Type', '$Account_Status', '$Referrer', '$Balance')";
$registered = mysqli_query($connection, $query);
if ($registered) {
echo "Register successful!";
}
// End the connection
mysqli_close($connection);
}
insert_user("#user1", "user#gmail.com", "user12345678", "1234", "Member", "Active", "0", "0");
?>
You are inserting a string value of 'NULL' into your primary key, you either remove the quotes '' or omit ID from the query.
Remove Quotes:
$query = "INSERT INTO `users` (`ID`, `Username`, `Email`, `Password`, `PIN`, `Registration_Date`, `Account_Type`, `Account_Status`, `Referrer`, `Balance`) VALUES (NULL, '$username', '$email', '$password', '$PIN', '$Registration_Date', '$Account_Type', '$Account_Status', '$Referrer', '$Balance')";
Or Remove the ID column:
$query = "INSERT INTO `users` ( `Username`, `Email`, `Password`, `PIN`, `Registration_Date`, `Account_Type`, `Account_Status`, `Referrer`, `Balance`) VALUES ('$username', '$email', '$password', '$PIN', '$Registration_Date', '$Account_Type', '$Account_Status', '$Referrer', '$Balance')";

PHP/MySQLi Insert returns blank page

I've created a very basic PHP Create User form, on my personal machine it worked fine but since getting a proper host I've been encountering errors non stop. The first was that it was insecure to use the Date how I was so I disabled it, now I'm getting no errors but it's not inserting data to the table and redirects me to index.php but all I see is a blank white page. Any help?
<?PHP
include'../include_htm/global.htm';
error_reporting(-1);
//Connect to server and select databse.
$link = mysqli_connect("$DB_HOST", "$DB_USER", "$DB_PASS", "$DB_NAME")
or die ('Could not connect to database!');
//Grab information from post page
$reg_username=$_POST['username'];
$reg_password=$_POST['password'];
$email=$_POST['email'];
$avatar=$_POST['avatar'];
if($avatar == null) {
header("location:../register.php?no_avatar=true");
}
else
{
//Set variables
//$date = date('j\/m\/Y');
$false = "false";
$ipaddress = $_SERVER["REMOTE_ADDR"];
$role = "user";
//Encrypt Password With MD5
$encrypt_password=hash('sha256', $reg_password);
//Insert Information
$query = "INSERT INTO $DB_TABLE (username, password, email, role, ipaddress, avatar) VALUES ('$reg_username', '$encrypt_password', '$email', '$role', '$ipaddress', '$avatar')";
mysqli_query($link, $query);
mysqli_close($link);
//Select login details from database
$_SESSION['user'] = $reg_username;
//$query1 = "UPDATE $DB_TABLE SET avatar='$avatar' WHERE `username`='$reg_username'";
//mysqli_query($link, $query1);
//mysqli_close($link);
header("location:../index.php?welcome=true");
}
?>
//Insert Information
$stmt = $link->prepare("INSERT INTO `$DB_TABLE` (`username`, `password`, `email`, `role`, `ipaddress`, `avatar`) VALUES (?,?,?,?,?,?)");
/* bind parameters for markers */
$stmt->bind_param("ssssss", $reg_username, $encrypt_password, $email, $role, $ipaddress, $avatar);
/* execute query */
$stmt->execute();
mysqli_close($link);

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