Can anyone help with advising what may be wrong with my insert into syntax please ?
Working except i am receiving empty query message
// values sent from form
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$postcode=$_POST['postcode'];
$gender=$_POST['gender'];
$yob=$_POST['yob'];
/*********** CONNECT TO THE DATABASE ******/
//Step 1 CONNECT TO THE DATABASE
$db=mysql_connect ("localhost", “db_username, “db_password);
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
}
//Step2 SELECT THE DATABASE
$db_select = mysql_select_db(“db_name,$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
}
echo "Welcome $first_name!";
echo " Success, connected to database but maybe not the table";
// Insert data into database
//##############################I THINK PROBLEM MUST BE HERE IN THIS INSERT STATEMENT STATEMENT###################################
$sql="INSERT INTO newsletter-subscribers(first_name, last_name, email, postcode, gender, yob)VALUES('$first_name','$last_name','$email','$postcode','$gender','$yob')";
if(mysql_query($sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysql_error($db);
}
$result=mysql_query($sql);
Your query,
$sql="INSERT INTO newsletter-subscribers(first_name, last_name, email, postcode, gender, yob)VALUES('$first_name','$last_name','$email','$postcode','$gender','$yob')";
Your new query,
$sql = "INSERT INTO `newsletter-subscribers` (first_name, last_name, email, postcode, gender, yob) VALUES ('$first_name','$last_name','$email','$postcode','$gender','$yob')";
So, what has changed?
Added ticks around your table name.
Removed spaces which you didn't need to make query clearer.
Without the backticks around your table name, MySQL is treating it as newsletter minus subscribers. Which is wrong, add the ticks to tell MySQL that it is a table name.
Edit 1
This might be a copy & paste error, I'm not sure, however...
Your db connect is incorrect too, you aren't assigning any values to it as your quotes are not closed and are smart quotes.
Your connect,
$db = mysql_connect ("localhost", “db_username, “db_password);
Your new connect,
$db = mysql_connect("localhost", "db_username"," db_password");
Also,
$db_select = mysql_select_db(“db_name,$db);
To,
$db_select = mysql_select_db("db_name", $db);
Notice the difference in the quotes.
Edit 2
Your code is prone to SQL injection, you are still using MySQL even though it has been deprecated, you should use either MySQLi or PDO with prepared statements.
Not to mention your $_POST data is being passed on to the query without being sanitized, you should start using htmlspecialchars it would make it better and prevent XSS.
Your table name contains a dash, so you need to quote it. The backtick or back-quote character is used to quote symbol names in MySQL (such as the names of tables, columns, etc), so you would need something like this:
INSERT INTO `newsletter-subscribers` (first_name, ...
Related
$value2=$_POST['c_name'];
$value3=$_POST['c_vehicle_number'];
$value4=$_POST['c_phone'];
$value5=$_POST['c_email'];
these are the values stored in 1.php.
i want insert those values in 2.php.as below,
$sql="insert into customer_details(c_id,c_name,c_vehicle_number,c_phone,c_email) values ('','$value2','$value3','$value4','$value5')";
=====================================================
am using require('1.php');
which does not insert the values into the database.
what would be the soluton.?
In order to enter a values into the DB one must have a connection to the Database.
Create a connection to the relevant database.
Perform our desired query.
Example:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Explanation:
As you can see we first trying to retain a connection using mysqli_connect with the relevant DATABASE-ADDRESS, USERNAME, PASSWORDandDATABASE-NAME`
Than we're using mysqli_query to perform our query and we're passing it the connection we opened earlier + the query string we wish to perform.
More explanation could be found HERE
Important: This example isn't SQL-Injection protected, and it's highly important to you, to be protected against it. Read about it HERE
you can try this
$sql="INSERT into customer_details(c_id,c_name,c_vehicle_number,c_phone,c_email) VALUES ('".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."')";
you worte :
('','$value2','$value3','$value4','$value5') you did mistake here
it can be write
('".$value2."','".$value3."','".$value4."','".$value5."')
I am currently trying to send data from an HTML form (Proform.html) to a MYSQL database. I cannot figure out how to solve this problem that keeps occurring as I am new to php the error message I keep receiving is.
"Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\php\Proform.php on line 22"
It could be possable as I have used several different references to create this page of code that i have mixxed two different realeases of php. Though help would be appriciated Anyways code is as follows.
<?php
$dbname='*****';
$dbhost='localhost';
$dbpass='******';
$dbuser='******';
$dbhandle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("ecig",$dbhandle)
or die("Could not select examples");
$q = $dbhandle->query("INSERT INTO Persons (First_Name, Last_Name)
VALUES ('$_POST[First_Name]', yes)");
if (array_key_exists ('check_submit', $_POST ))
echo "Your Name is : {$_POST['First_Name']}<br />";
echo "Your Second Name is : {$_POST['Second_Name']}<br />";
echo "Your Email Address is : {$_POST['Email_Address']}<br />";
echo "Your Password Is : {$_POST['Password']}<br />";
?>
There is a problem in your query
Why are you calling the query using the database connection string.
You have to call it like this:
$con=mysql_connect($dbhost,$dbuser,$dbpass,$dbname);
$res=mysql_query("INSERT INTO Persons (First_Name, Last_Name) VALUES('$_POST[First_Name]', yes)");
mysql_close();
mysql_connect does not return any object .... so it does not have any function or property that you can access using -> operator . It returns a connection identifier
replace
$dbhandle->query("INSERT INTO Persons (First_Name, Last_Name)
VALUES ('$_POST[First_Name]', yes)");`
with
mysql_query("INSERT INTO Persons (First_Name, Last_Name)
VALUES ('$_POST[First_Name]', yes)")
I advice you to start learning mysqli or PDO since mysql functions are retarded and no longer maintained
I have contact form at my wordpress site which is delivered by ajax, and sent to my mail. I also wanted to save the results in a database so I wrote this query, but it gives me and syntax error, but I can't find anything wrong in this code:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql="INSERT INTO wp_contactform (Nimi, Puhelin, E-mail, Viesti, IP, Day)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The jquery script that sends it works, and the mail is sent, but this doesn't save.
Quote the column name E-mail with backticks (`). MySQL is interpreting this in two parts at the moment.
Note also, (as per my comment) that your code is wide open to SQL injection attacks. It is much better to use properly parameterised SQL queries.
SQL injection example:
"INSERT INTO table (field) VALUE ('$_POST[var]')"
If you post the value "'; DROP TABLE table; --" then you have a valid SQL string that inserts an empty string, then attempts to drop the table. Substitute whatever harmful statement you want.
and also you should use mysql_real_escape_string() or prepared statements. if your query data have any special characters it can blow your query it also help you from sql injection too.
http://php.net/mysql_real_escape_string
http://php.net/pdo
Your SQL request should be written as below:
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')"
SQL fields using non-alphanumeric characters have to be escaped with backticks (`)
This should work
<?php
$con = mysql_connect("localhost", "username", "password");
if(!$con){
die('Could not connect: '.mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('".mysql_real_escape_string($_POST['Nimi'])."','".
mysql_real_escape_string($_POST['Puhelin'])."','".
mysql_real_escape_string($_POST['Sposti'])."','".
mysql_real_escape_string($_POST['Tiedot'])."','".
mysql_real_escape_string($_POST['Gotcha'])."','".
mysql_real_escape_string($_POST['Day'])."')";
if(!mysql_query($sql, $con)){
die('Error: '.mysql_error());
}
echo "1 record added";
mysql_close($con);
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("pilot", $con);
$sql = "INSERT INTO logs (id, userid, date, plane, from, to, blocksoff, takeoff,
landing, blockson, flighttime, traveltime, tachobefore, tachoafter, tacho,
hobbsbefore, hobbsafter, hobbs, landings) VALUES ('$nfid', '$nfuserid',
'$nfdate', '$nfplane', '$nffrom', '$nfto', '$nfblocksoff', '$nftakeoff',
'$nflanding', '$nfblockson', '$nfflighttime', '$nftraveltime', '$nftachobefore',
'$nftachoafter', '$nftacho', '$nfhobbsbefore', '$nfhobbsafter', '$nfhobbs',
'$nflandings')";
mysql_query($sql);
there ain't nothing wrong with the $sql, it seems like it just wont query.. :(
id|userid=int(11)
date=date
plane|from|to=text
blocksoff|takeoff|landing|blockson=time
flighttime|traveltime|tachobefore|tachoafter|tacho|hobbsbefore|hobbsafter|hobbs|landings=double
all of the $ variables come from a textbox (if it matters)
May be some of the column names are MySql reserved words (especially from and to). Please escape them.
INSERT INTO logs (`id`, userid, date, plane, `from`, `to` ...)
You should always be checking for errors:
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Kind of an open ended question....
Are any of your variables returning NULL values? If you are trying to insert NULL into the database, and the database column isn't set to accept NULL values, that could be causing an error.
You need to see what the query is actually doing. If you have any single quotes or other invalid character from the textbox, that could be screwing you up.
Also, for your own personal improvement, look up PDO. It helps you write much more secure queries through the use of prepared statements.
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):
"Connected to databaseError: 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 ''test' ('name') VALUES ('daniel')' at line 1"
The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?
Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.
HTML
<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
PHP (insert.php)
<?php
$dbhost = 'localhost';
$dbname = 'carbon_db';
$dbuser = 'username';
$dbpass = 'password';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
else
{
echo 'Connected to database';
}
mysql_select_db($dbname, $con);
$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Drop the quotes around the table name or change them to back ticks:
Change:
$sql="INSERT INTO 'test' ('name') VALUES ('$_POST[namefield]')";
To:
$sql="INSERT INTO test ('name') VALUES ('$_POST[namefield]')";
Or
$sql="INSERT INTO `test` ('name') VALUES ('$_POST[namefield]')";
It's often best to use backticks for MySQL as like any other storage engines it has it's own reserved names and it's own reserved insert practices.
try with
$sql = "INSERT INTO `test` (`name`) VALUES ('".$_POST['namefield']."')";
Change the single quotes surrounding the table name and the column name to backticks. Or get rid of them all together.
$sql="INSERT INTO `test` (`name`) VALUES ('{$_POST['namefield']}')";
Also, don't reference associative arrays ($_POST) directly in a string without using {} syntax or breaking up the string - what you have done there issues an E_NOTICE and should be avoided.
Read this thoroughly - you'd be amazed what you can (and can't) legally do in PHP strings...
try using ` instead of ' when refering to table/column names
$sql="INSERT INTO `test` (`name`)
VALUES ('$_POST[namefield]')";
Remove the single quotes around your sql statement and replace with back-tics (not sure even they are necessary):
$sql="INSERT INTO `test` ('name')
VALUES ('$_POST[namefield]')";