Query Fails whenever I want to insert - php

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

Related

MySQL Entry to Database Not Working

I'm going through a course on MySQL, and I'm learning how to make a user entry bit of code (email and password) where the info in the script will be put into the database on phpMyAdmin. I can't seem to get it to work? My code doesn't have any errors when I put it through an error checker. I'm also completely new to PHP and MySQL. I know it can find the database, because I can update existing data.
<?php
$link = mysqli_connect("host", "username", "password", "username");
if (mysqli_connect_error()) {
die ("There was an error connecting to the database");
}
$query = "INSERT INTO `users` (`email`, `password`) VALUES('email', 'password')";
mysqli_query($link, $query);
$query = "SELECT * FROM users";
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo "Your email is ".$row[1]." and your password is ".$row[2];
}
?>
Created a refined version. Check it.
<?php
$link = mysqli_connect("host", "username", "password", "username");
if (mysqli_connect_error()) {
die ("There was an error connecting to the database");
}
$query = "INSERT INTO `users` (`email`, `password`) VALUES('email', 'password')";
$result = mysqli_query($link, $query);
if($result != false)
{
echo "The record has been successfully inserted.<br>";
}
else
{
echo "Error Occured in the INSERT query.<br>Error : ".mysqli_error($link);
}
$query = "SELECT * FROM users";
$result = mysqli_query($link, $query);
if($result != false)
{
echo mysqli_num_rows($result)." Records found.<br>";
while($rows = mysqli_fetch_array($result))
{
echo $rows["email"]."<br>";
}
}
else
{
echo "Error Occured in the SELECT query.<br>Error : ".mysqli_error($link);
}
mysqli_close($link);
?>
Update
It turns out I didn't set the auto_increment setting, therefore making the way I set up my database incorrect! He set up another database in the tutorials I was going through, and I found out that as he did it. Thank you everyone for the effort to help me solve my problem!
Why you don't try receiving them with php?
And simply make
$email= $POST['email']
$password= $POST['password']
And change the query to
$query = "INSERT INTO `users` (`email`, `password`) VALUES(" .$email. ", ". $password.")";

not response for database

This is the code for database connection in php:
<?php
$connection = mysql_connect("localhost", "root", "root"); // Establishing Connection with Server
$db = mysql_select_db("fimos", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$gender = $_POST["gender"]; //declare gender
$race = $_POST["race"];
$ic = $_POST["icno"];
$name = $_POST["name"];
$old_ic = $_POST["oldic"];
$add1 = $_POST["add1"];
$add2 = $_POST["add2"];
$add3 = $_POST["add3"];
$postcode = $_POST["postco"];
$town = $_POST["tow"];
$state = $_POST["state"];
$home_con = $_POST["homep"];
$fax_contact = $_POST["fax"];
$hp_con1 = $_POST["mobi1"];
$hp_con2 = $_POST["mobi2"];
$email = $_POST["email"];
if($ic !=''||$email !=''){
//Insert Query of SQL
$query = mysql_query("INSERT INTO customer_info(cust_gender, cust_race, cust_ic,
cust_name, cust_old_ic, cust_add1, cust_add2, cust_add3, cust_postcode,
cust_town, cust_state, cust_home_con, cust_fax_contact, cust_hp_contact1,
cust_hp_contact2, cust_email)
VALUES ('$gender', '$race', '$ic' , '$name', '$old_ic', '$add1', '$add2',
'$add3', '$postcode', '$town', '$state', '$home_con', '$fax_contact',
'$hp_con1', '$hp_con2', '$email')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
Hi guys, I want to ask about the database connection, is it my code wrong somewhere?
Because I cant found any error in the code.
I click button register should come over this page to store the data.
when I come to this page display all blank.
I try to change the database name also no response.
I hope you guys can help me.
Thanks.
It should be:
$connection = mysql_connect("localhost", "root", ""); //empty the third parameter. If you have password then insert that in your third parameter
Paste this code inside your if condition so that it will return error from your sql query.
if (!$query) {
die('Invalid query: ' . mysql_error());
}
Try to use the PDO extension instead of mysql & mysqli function. The mysql_* functions are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi there are lots of benefits of using PDO over mysqli.
Add the above code
if($ic !=''||$email !=''){
$query = mysql_query("your query");
if (!$query) {
die('Invalid query: ' . mysql_error());
} else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
}

PHP message "Error: No database selected", concernig this script

I have this script, but i don't know what could be wrong here when I hit "post" button on the main page. Where the error can come from?
The page script:
<?php
session_start();
include("dbconnection.php");
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$messages = clean($_POST['message']);
$user =clean($_POST['name']);
$pic =clean($_POST['name1']);
$poster =clean($_POST['poster']);
$sql="INSERT INTO message (messages, user, picture, date_created, poster)
VALUES
('$messages','$user','$pic','".strtotime(date("Y-m-d H:i:s"))."','$poster')";
mysql_query("UPDATE messages SET picture = '$pic' WHERE FirstName='$user'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header("location: lol.php");
exit();
$name=$_POST['name'];
$pic=$_POST['name1'];
mysql_query("UPDATE messages SET picture = '$pic' WHERE FirstName='$name'");
?>
This is the dbconnect file:
$con = mysql_connect("hostname","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("asl", $con);
?>
Ensure you have selected your db using mysql_select_db
mysql_connect('hostname','username','password') or die("not able to connect");
mysql_select_db('myDatabase');
And mysql_ extensions are deprecated.. Dont use it
this errors seems to be caused by either selecting wrong database or not selecting it.
check dbconnection.php and for this line in it
mysql_select_db("your_database_name",$your_connection);
See whether this line is present and pointing to database or not and make sure this databse exists
Update It seems that your file is not being included try require() so that it produces fatal error and you can see file s being including or not
require("dbconnection.php"); // will produce fatal errors
First of all mysql_connect is outdated and unsecure, better use PDO instead
<?php
session_start();
include("dbconnection.php");
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$messages = clean($_POST['message']);
$user =clean($_POST['name']);
$pic =clean($_POST['name1']);
$poster =clean($_POST['poster']);
$sql = $db->prepare("INSERT INTO message (messages, user, picture, date_created, poster) VALUES (:messages, :user, :picture, :date_created, :poster)");
$sql->bindParam(':messages', $messages);
$sql->bindParam(':user', $user);
$sql->bindParam(':picture', $pic);
$sql->bindParam(':date_created', strtotime(date("Y-m-d H:i:s")));
$sql->bindParam(':poster', $poster);
$stmt = $db->prepare("UPDATE messages SET picture = :picture WHERE FirstName = :user");
$stmt->bindParam(':picture', $pic);
$stmt->bindParam(':user', $user);
$stmt->execute();
if (!$sql->execute())
{
die('Error: ' . mysql_error());
}
$name=$_POST['name'];
$pic=$_POST['name1'];
$stmt_2 = $db->prepare("UPDATE messages SET picture = :picture WHERE FirstName = :name");
$stmt_2->bindParam(':picture', $pic);
$stmt_2->bindParam(':name', $name);
$stmt_2->execute();
header("location: lol.php");
?>
This is the dbconnect file:
<?php
//Connect to sql db
try {
$user_db = "username";
$pass_db = "password";
$db = new PDO('mysql:host=localhost;dbname=asl', $user_db, $pass_db);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>

Inserting user updates into SQL with PHP

I think I am really close now - there are no more nasty Orange boxes with errors in - the only problem I can see at the moment is that once I update the table (after the
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')";
) I get the message "No rows updated" echo to the screen!
Any ideas what the problem is?
Thanks.
<?php
//Start session
session_start();
$_SESSION['SESS_LOGIN'];
//Include database connection details
require_once('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
$employ = clean($_POST['employer']);
$address = clean($_POST['flat']);
?>
<?Php
//Insert employer and address into database row for logged in user.
$login_name = $_POST['login_name'] ;
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')" ;
$result = #mysql_query($link, $qry);
//Check whether the query was successful or not
if(!$result) {
echo "No rows updated";
exit();
}else {
echo "Success";
}
?>
Don't use VALUES, use SET:
"UPDATE `members` SET `employer` = '".$employ."', `flat` = '".$address."' WHERE `login`='".$login_name."'"
First of all you should not suppress error messages by using the # opperator if you are looking for issues in your code. Also you are using the wrong parentheses (' instead of `). The rest of your code looks fine. maybe you need to give us some info about the database structure otherwise

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