Issue with PHP and MySQL Database - php

Here is my main PHP code:
<?php
define('dbServer', 'localhost');
$dbUsername = 'root';
$dbPassword = '';
define('dbName', '1');
$dbConnection = mysqli_connect(dbServer, $dbUsername, $dbPassword, dbName);
if(!$dbConnection){
die("Unsuccessful Connection: " . mysqli_connect_error());
}
// All user data will be taken from the form //
$emailAddress = $_POST['emailaddress'];
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$streetAddress = $_POST['streetaddress'];
$phoneNumber = $_POST['phonenumber'];
$comments = $_POST['comments'];
$sql = "INSERT INTO user-submission (email, firstName, lastName, address, phoneNumber, comment) VALUES ('$emailAddress', '$firstName', '$lastName', '$streetAddress', '$phoneNumber', '$comments')";
$result = mysqli_query($dbConnection, $sql);
if (!$result){
die('Error: ' . mysqli_connect_error());
}
?>
My SQL database contains the rows ID, email, firstName, lastName, address, phoneNumber, comment. They are in a database called '1' (for testing purposes) and a table called 'user-submission'.
I have been unable to query this information into my table. I have been successful prior to this on other SQL and PHP pairings. What am I doing wrong this time?

Add this right below the opening php tag at the top then the server will tell you what the error is. Copy the error here if you need help decyfering
error_reporting( E_ALL );

First you need to make changes so hackers don't abuse your code.
Just wait till johnny;drop tables; comes by and wipes out your database.
// All user data will be taken from the form //
$emailAddress = mysqli_real_escape_string($dbConnections,$_POST['emailaddress']);
$firstName = mysqli_real_escape_string($dbConnections,$_POST['firstname']);
$lastName = mysqli_real_escape_string($dbConnections,$_POST['lastname']);
$streetAddress = mysqli_real_escape_string($dbConnections,$_POST['streetaddress']);
$phoneNumber = mysqli_real_escape_string($dbConnections,$_POST['phonenumber']);
$comments = mysqli_real_escape_string($dbConnections,$_POST['comments']);
$sql = "INSERT INTO `user-submission` (email, firstName, lastName, address, phoneNumber, comment) VALUES (?,?,?,?,?,?)";
$prep=$dbConnections->prepare($sql);
$prep->bind_param("ssssss",$emailAddress,$firstName,$lastName,$streetAddress,$phoneNumber,$comments);
#actually puts everything together, and puts it in the database
$prep-execute();

Related

I am getting a Syntax Error in SQL

Having trouble submitting data to a database because of syntax error.
Database Structure
database: red_fungi
username: fungi_47
password: *******
Table Structure:
columns > type
id > int(11)
first_name > text
last_name > text
email > text
phone > text
website > text
description > text
As well as the php code:
<?php
$servername = "localhost";
$username = "fungi_47";
$password = "********";
$dbname = "red_fungi";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['first_name']);
$last_name = mysqli_real_escape_string($link, $_POST['last_name']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$phone = mysqli_real_escape_string($link, $_POST['phone']);
$website = mysqli_real_escape_string($link, $_POST['website']);
$comment = mysqli_real_escape_string($link, $_POST['comment']);
$hosting = mysqli_real_escape_string($link, $_POST['hosting']);
$sql = "INSERT INTO contact (id, first_name, last_name, email, phone, website, description, hosting)
VALUES (NULL, $first_name, $last_name, $email, $phone, $website, $comment, $hosting)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When submitting, I see that the post has been successful:
first_name=Bill&last_name=Nye&email=bill%40nye.com&phone=8888888888&website=billnyefungi.com&comment=help%20me%20make%20a%20fungi%20website&hosting=yes
but the post response shows the following error:
Error: INSERT INTO contact (id, first_name, last_name, email, phone, website, description, hosting)
VALUES (NULL, , , , , , , )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 ' , , , , , )' at line 2
However I've checked the syntax and can't see anything wrong with it. Any ideas what's going wrong?
Your sql statement needs to look more like this:
$sql = "INSERT INTO `contact` (`id`, `first_name`, `last_name`, `email`, `phone`, `website`, `description`, `hosting`)
VALUES (NULL, '{$first_name}', '{$last_name}', '{$email}', '{$phone}', '{$website}', '{$comment}', '{$hosting}')";
The first thing I do when I have a problem like this is echo out the sql and see if there are obvious problems
and follow up on all the data validation & security points made by other users.
Your code is assuming that $_POST['XXX'] will be populated, and it isn't. Thats what all those ,,,,,,,, mean in the error.
Instead, first check if $_POST['XXX'] is created, and has a value prior to using it.
if ((isset($_POST['first_name'])) && (!empty( $_POST['first_name'])) ) {
//do query and rest of your script
} else { die('Need form input');}

Input values aren't being stored in a MySQL database

I've created a simple login form. I'm not able to store user input values at the back-end. Here's the full code for your reference:
dp.php
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'list') or trigger_error(mysqli_error());
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$email = $_POST['email_id'];
$password = $_POST['password'];
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES ('$first_name', '$last_name', '$email','$password')";
mysqli_query($dbc, $query) or trigger_error(mysqli_error($dbc));
echo 'login created';
mysqli_close($dbc);
?>
remove single quote from php variable
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES
($first_name, $last_name, $email,$password)";
if your data contain string that will put in "" or ''
$query = "INSERT INTO login_list (first_name, last_name, email,password) VALUES
('".$first_name."','".$last_name."', '".$email."','".$password."')";
i hope this will solve your problem if $_POST get correct data . you have to concat string at that time

Shared login session between EasyAppointments and Bootstrap website

This is my first post on stackoverflow, though I have done extensive research using it along with other sources on a regular basis (including the subject I need help with here.)
To be concise, I am working on a shared session/login/register between a client's site and the EasyAppointments scheduling application. While compiling the config.php for the registration form on my client's site I received this error. I have searched everywhere, please help me understand this:
INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles) VALUES(testing, test, 000000000, 000000000, 123 example street, Birmington, Alabama, 00000, , )INSERT INTO `ea_user_settings` (username, password, salt, working_plan, notifications, google_sync, google_token, google_calendar, sync_past_days, sync_future_days) VALUES(TestUser, 0000000000, , , 0, , , , , )
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 ' , 0, , , , , )' at line 2
Here is my config.php code (please excuse my unorthodox variables for sql1/sql2):
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', '####');
define('DB_USER','####');
define('DB_PASSWORD','####');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); $db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$mobile_number = $_POST['mobile_number'];
$phone_number = $_POST['phone_number'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip_code = $_POST['zip_code'];
$noteboy = $_POST['notes'];
$privs = $_POST['id_roles'];
$email = $_POST['email'];
$nick = $_POST['nick'];
$password = $_POST['password'];
$salt = $_POST['salt'];
$working_plan = $_POST['working_plan'];
$notifications = $_POST['notifications'];
$google_sync = $_POST['google_sync'];
$google_token = $_POST['google_token'];
$google_calendar = $_POST['google_calendar'];
$sync_past_days = $_POST['sync_past_days'];
$sync_future_days = $_POST['sync_future_days'];
$bang = "INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles)
VALUES($first_name, $last_name, $mobile_number, $phone_number, $address, $city, $state, $zip_code, $noteboy, $privs)";
echo $bang;
$banger = "INSERT INTO `ea_user_settings` (username, password, salt, working_plan, notifications, google_sync, google_token, google_calendar, sync_past_days, sync_future_days)
VALUES($nick, $password, $salt, $working_plan, $notifications, $google_sync, $google_token, $google_calendar, $sync_past_days, $sync_future_days)";
echo $banger;
$result = mysql_query($bang); mysql_query($banger);
if($result) {
echo "Successfully updated database";
} else {
die('Error: '.mysql_error($con));
}
mysql_close($con);
I doubt you're storing phone numbers as integers, so you should be quoting all those zeroes. SQL doesn't like missing values in the VALUES clause, so you need to fix that to default to a format that's appropriate for your fields, such as empty string, a zero or a NULL. You also need to think about escaping too to avoid errors and SQL injection vulnerabilities - using PDO might be good idea if you're early on in your project, and you should definitely switch to mysqli at the very least.
Your check for query failure only looks at your first query - you should check both.
Anyway, here's how you might apply escaping and quoting to avoid the error you're seeing using your current approach:
$bang = "INSERT INTO `ea_users` (first_name, last_name, mobile_number, phone_number, address, city, state, zip_code, notes, id_roles)
VALUES('".
mysql_real_escape_string($first_name)."','".
mysql_real_escape_string($last_name)."','".
mysql_real_escape_string($mobile_number)."','".
mysql_real_escape_string($phone_number)."','".
mysql_real_escape_string($address)."','".
mysql_real_escape_string($city)."','".
mysql_real_escape_string($state)."','".
mysql_real_escape_string($zip_code)."','".
mysql_real_escape_string($noteboy)."','".
mysql_real_escape_string($privs)."')";

Inserting into database with PHP not working

below is my php script to input data into my database from my form. You can see my form here... http://studentnet.kingston.ac.uk/~k1202101/workshop2/CreateNewAccount.html
I get an error message when I try to submit the form. The error message I get is
'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 'Name, Medical Information, First Name, Membership Type, D.O.B, Gender, Membershi' at line 1'
I have gone over my code but still cant see where I have gone wrong? Any help would be greatly appreciated.
<?php
define('DB_NAME', 'demo'); //**your database name
define('DB_USER','alex'); //**your user ID
//**your password
define('DB_HOST', 'localhost'); //**your local host or KU host
$link = mysql_connect(DB_HOST, DB_USER);
if(!$link)
{
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected)
{
die('Can\'t use'. DB_NAME . ':' . mysql_error());
}
$value1 = $_POST['Last Name'];
$value2 = $_POST['Medical Information'];
$value3 = $_POST['First Name'];
$value4 = $_POST['Membership Type'];
$value5 = $_POST['D.O.B'];
$value6 = $_POST['Gender'];
$value7 = $_POST['Membership Referral'];
$value8 = $_POST['Trainer Required'];
$value9 = $_POST['Membership Number'];
$value10 = $_POST['Contract'];
$value11 = $_POST['House Number/Street'];
$value12 = $_POST['City'];
$value13 = $_POST['County'];
$value14 = $_POST['Postcode'];
$value15 = $_POST['Tel'];
$value16 = $_POST['E-Mail'];
$value17 = $_POST['Bank Branch'];
$value18 = $_POST['Card Holder Name'];
$value19 = $_POST['Card Number'];
$value20 = $_POST['Security Code'];
$sql ="INSERT INTO test(Last Name, Medical Information, First Name, Membership Type, D.O.B, Gender, Membership Referral, Trainer Required, Membership Number , Contract, House Number/Street, City, County, Postcode, Tel, E-Mail, Bank Branch, Card Holder Name, Card Number, Security Code) VALUES('$value1', '$value2', '$value3', '$value4','$value5','$value6','$value7','$value8','$value9','$value10','$value11','$value12','$value13','$value14','$value15', ,'$value16',,'$value17',,'$value18',,'$value19',,'$value20')";
if (!mysql_query($sql))
{
die('Error:'.mysql_error());
}
mysql_close();
?>
Column names with space needs to back ticks as
`Last Name`
So in the insert query you need to backtick them.
use back ticks, and overall check at your query :
$sql ="INSERT INTO test(Last Name, Medical Information, First Name, Membership Type, D.O.B, Gender,
Membership Referral, Trainer Required, Membership Number , Contract, House Number/Street, City,
County, Postcode, Tel, E-Mail, Bank Branch, Card Holder Name, Card Number, Security Code)
VALUES('$value1', '$value2', '$value3','$value4','$value5','$value6','$value7','$value8',
'$value9','$value10','$value11',
'$value12','$value13','$value14','$value15', ,'$value16',,'$value17',,'$value18',,'$value19',,'$value20')";
between value15 and value16 you have double , and so on between value 17 and 18.
Clean your query.

PHP white screen of death every time. What am I doing wrong?

I'm a complete noob to PHP and working with mysql so you know I do however have a great deal of experience with HMTL and CSS. All I need is for a form on my site to upload the information in the form to my database. The problem is that clicking the "submit" button just opens up a blank tab with the address of my .php file in it and displays a blank white screen. The .php is below.
<?php
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
$sql = "INSERT INTO $usertable (firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
$sql="INSERT INTO $usertable (firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('".$_POST[firstName]."', '".$_POST[lastName]."', '".$_POST[streetAddress]."', '".$_POST[city]."', '".$_POST[state]."', '".$_POST[zip]."', '".$_POST[country]."', '".$_POST[email]."', '".$_POST[phone]."', '".$_POST[badgeName]."')";
?>
Now from what I've read this is usually caused by some kind of error in the code. This is difficult for me as I don't know PHP very well and almost everything in the page was taken from other peoples code. Most of it from the code helps from godaddy.com (where the site and database are hosted).
I've tested to make sure that PHP is supported and enabled and it is. I have a form mailer that already functions just fine. I have setup a DNS, I have tried multiple different syntaxes, I have called tech support to see if it is something on their end, I've migrated my sites from windows to linux and every thing I change results in the exact same blank white screen. I have no doubt that after all this it's going to be something that's stupidly easy to fix or blatantly obvious but if anybody could take a look and see what I'm missing I would be very grateful.
My new code after taking in some of the answers posted. I'm still getting a NOTICE and it's still not inserting anything into my database.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
//connect to mysql
$link_id = mysql_connect($hostname, $username, $password);
if (!$link_id) {
die("Unable to connect to database! Please try again later. error:".mysql_errno());
}
//make sure your DB exists
if (!mysql_select_db($dbname)) die ("Connected to mysql but could not connect to the DB. error:".mysql_errno());
//avoid sql_injection
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$streetAddress = mysql_real_escape_string($_POST['streetAddress']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip = mysql_real_escape_string($_POST['zip']);
$country = mysql_real_escape_string($_POST['country']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$badgeName = mysql_real_escape_string($_POST['badgeName']);
//write the query
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
//then you'll need to execute the query :)
mysql_query($sql);
?>
From what I can tell, this code just connects to a database and sets a variable $sql. Are you actually executing the query anywhere? Are you doing anything to print something on the screen?
$_POST[firstName] should be $_POST['firstName'] and so on and
mysql_query($sql) or die('MySQL Error: ', mysql_error());
echo 'Data inserted';
You shouldn't not be using mysql_ now, its deprecated. Do it with PDO
first of all
$_POST[firstname] should be $_POST['firstname']
third
mysql_query($sql,$conn);
second
$conn=mysql_connect(your parameters);
Include this two lines at the very top of your php code:
error_reporting(E_ALL);
ini_set('display_errors', '1');
It is going to enable error reporting and so you will be able to debug your script.
Maybe the problem is that the reading of $_POST variables (and of any array type variable) should be made with 'quotes' when using string index names:
$_POST[firstName] must be written as follows:
$_POST['firstName']
A good way of making this query more secure (against sql injection attacks for example) is to scape the values in POST instead of passing it directly to the query.
$firstName = mysql_real_escape_string($_POST['firstName']);
The value in POST will be scaped so you can pass it to your SQL.
Try to make that will all your variables:
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
Finally you need to actually execute the query:
mysql_query($sql);
If it goes ok you'll see no errors, but be shure to enable error reporting to this script. When everything it's ok remember to remove the error reporting.
Like the other guys said, put the comments in the array reference. That being said you really need to escape the $_POST variables to avoid SQL Injection, its also easier to debug if the code is clearly ordered :)
With ordered code you can type echo "some text"; at any touch point you want to so you can see where the code breaks.
Also switching on error reporting in your php.ini or in code (http://php.net/manual/en/function.error-reporting.php) would be the best bet for watching the errors that you can't predict.
<?php
$hostname = "myHostName";
$username = "PreRegCustomers";
$dbname = "PreRegCustomers";
$password = "myPassword";
$usertable = "CustomerInfo";
//connect to mysql
$link_id = mysql_connect($hostname, $username, $password);
if (!$link_id) {
die("Unable to connect to database! Please try again later. error:".mysql_errno());
}
echo "connected to mysql";
//make sure your DB exists
if (!mysql_select_db($dbname)) die ("Connected to mysql but could not connect to the DB. error:".mysql_errno());
echo "connected to database";
//avoid sql_injection
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$streetAddress = mysql_real_escape_string($_POST['streetAddress']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip = mysql_real_escape_string($_POST['zip']);
$country = mysql_real_escape_string($_POST['country']);
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$badgeName = mysql_real_escape_string($_POST['badgeName']);
echo "sanitised input";
//write the query
$sql = "INSERT INTO $usertable
(firstName, lastName, streetAddress, city, state, zip, country, email, phone, badgeName)
VALUES ('$firstName', '$lastName', '$streetAddress', '$city', '$state', '$zip', '$country', '$email', '$phone', '$badgeName')";
echo "build query: ".$sql;
//then you'll need to execute the query :)
if (mysql_query($sql))
echo "query success";
else
echo "query failed";
//ps you can ignore the last? >

Categories