$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."')
Related
I have been developing a website on localhost with xampp and everything worked perfect. so i moved to a web host for the first time. I have edited my connection string to fit the web server and it connects fine but when i tried testing the registration page i designed it doesn't insert data into the database. I tried a simple insert statement on a separate script
<!DOCTYPE html>
<html>
<body>
<?php
$conn = mysql_connect("localhost", "my_db_user_name", "my_db_password");
$db = mysql_select_db("my_db_name");
$query1 = mysql_query("INSERT INTO users firstname VALUES 'Patrick'",$conn);
if($query1) {
echo "Yes";
} else {
echo "didn't work";
}
echo mysql_error($query1);
?>
</body>
</html>
It returned the didn't work and didn't insert anything neither did it echo any error. But when i tried a select statement and echo the result of the query it worked so its safe to say my connection is valid.
I also went to my cpanel phpmyadmin interface and tried the same insert statement it didn't work but returned:
1064 - 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 'firstname VALUES 'Patrick'' at line 1.
I tried with and without back ticks the same thing. but i can select query.
You missed the correct syntax for the insert.
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Example from w3schools:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
http://www.w3schools.com/php/php_mysql_insert.asp
Your query needs to look like this
INSERT INTO (columns) VALUES (values)
So you will get
INSERT INTO users (firstname) VALUES ('Patrick');
Dude... one second google, and you would have your answer.
http://www.w3schools.com/sql/sql_insert.asp
Also, the error says there is a SYNTAX ERROR. It is so difficult to understand? Why you don't simply check your syntax?
INSERT INTO users (firstname) VALUES ('Patrick')
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, ...
I'm updating or inserting multiple rows in database tables using Mysqli and multi_query. They work fine when I use them on my local MAMP server but break down when I take them online. On the remote server only three of the four queries are performed...
Both environments have PHP and mysql version 5+ and include "PHP extension: mysqli". The only difference I see is the phpMyAdmin version. The remote server has 3.5.6, my local MAMP server has 4.2.5. Could this have an influence?
I'm of course changing passwords and all variables should be valid since they work locally.
I'm at a loss... Thanks!
$mysqli = new mysqli("localhost", "root", "root", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$sql = "INSERT INTO categories (id, name, descr) VALUES ('$id1', '$name1', '$descr1') ON DUPLICATE KEY UPDATE name='$name1', descr='$descr1';";
$sql.= "INSERT INTO categories (id, name, descr) VALUES ('$id2', '$name2', '$descr2') ON DUPLICATE KEY UPDATE name='$name2', descr='$descr2';";
$sql.= "INSERT INTO categories (id, name, descr) VALUES ('$id3', '$name3', '$descr3') ON DUPLICATE KEY UPDATE name='$name3', descr='$descr3';";
$sql.= "INSERT INTO categories (id, name, descr) VALUES ('$id4', '$name4', '$descr4') ON DUPLICATE KEY UPDATE name='$name4', descr='$descr4';";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}else{
echo("Succes.");
}
$mysqli->close()
UPDATE:
Replacing the queries with a single query does work but not very do-able in all scenarios and requires a lot of re-writing... Using hard-coded variables does not help.
$sql2 = "INSERT INTO categories (id, name, descr) VALUES ('$id1', '$name1', '$descr1'), ('$id2', '$name2', '$descr2'), ('$id3', '$name3', '$descr3'),('$id4', '$name4', '$descr4')
ON DUPLICATE KEY UPDATE name=VALUES(name), descr=VALUES(descr)";
Fixed the issue by using the 'Object oriented style' as shown on php.net. Still not sure why my previous approach only worked locally but okay, lets call it fixed.
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
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);
I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Sometimes an input field in the HTML form will be left blank and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:
Home team: Blue team
Away team: [blank]
Result: Won
The following is inserted into my database:
Home team: Blue team
Away team: ' '
Result: Won
What I want to be inserted/not inserted is:
Home team: Blue team
Away team: NULL
Result: Won
I've hunted hours for a solution. Can anyone help? Thank you.
Well it will insert the final value only , because you are executing the $sql and the last values of $sql is "INSERT INTO scores (result) VALUES ('$_POST[result]')"; You are overiding the previous values by putting same variable name.
Also (!empty($_POST[hometeam])) remove the !empty if the fields can be blank sometimes.
You are overwriting your SQL statements each time. Beacue your 'result' field isn't blank, you are setting your SQL statement to:
"INSERT INTO scores (result) VALUES ('$_POST[result]')"
This is the only statement which is then being executed - your other values are being ignored as they are not part of this statement.
What you need to do is set up your variables first:
$hometeam = isset($_POST['hometeam']) ? $_POST['hometeam'] : NULL;
$awayteam = isset($_POST['awayteam']) ? $_POST['awayteam'] : NULL;
$result = isset($_POST['result']) ? $_POST['result'] : NULL;
You can then do your database interaction:
$sql = "INSERT INTO scores hometeam, awayteam, result VALUES $hometeam, $awayteam, $result";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
I should say that I haven't included any security on this - you should look into PDO or prepared statements to make sure your database isn't open to SQL Injection.
Hope this helps!
First off, there's a huge security flaw in this code, which is not sanitizing your inputs. A user could insert whatever they like and it's executed on the DB without any checking. This is bad.
At the very least, you should be using something like mysql_real_escape_string(), even though even that is not exactly the best thing for the job (Google PHP + PDO for example).
Secondly, you're actually executing one query using one variable. If $_POST['result'] is set, then $sql will always be the last value. What you might want to do is make the query like so:
$query = 'INSERT INTO scores ('.$fields.') VALUES ('.$values.')';
And construct the $fields and $values variables using your if(!empty( .. )) code.
But to reiterate SANITIZE YOUR INPUTS
3 insert into statements will insert 3 records, with unspecified fields left as null or default.
you must use 1 insert into statement, something like:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
#$sql="INSERT INTO scores (hometeam,awayteam,result) VALUES ('{$_POST[hometeam]}','{$_POST[awayteam]}','{$_POST[result]}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
here, unspecified values will come as empty string, if that is a problem, first assign them to 3 seperate variables with ifs (e.g. set empty ones to null), then use them
I think there is some problem with the declaration of name of your input field in you html form. Make sure, $_POST[hometeam] must be the same input name in your form
Example:
In your form
<input type="text" name="hometeam" value="" />
In your PHP
if (!empty($_POST[hometeam])) {
$sql="INSERT INTO scores (hometeam) VALUES ('$_POST[hometeam]')";
}
And also, please use addslashes or mysql_real_escape_string in your post values before adding it on the database.
Look at this link below:
http://php.net/manual/en/function.addslashes.php
http://php.net/manual/en/function.mysql-real-escape-string.php
if (!empty($_POST['hometeam'])) {
$sql="INSERT INTO scores (hometeam) VALUES ('" . $_POST['hometeam'] . "')";
}
Notice the single quotes around the 'hometeam' part.
You should also clean that using mysql_real_escape_string($_POST['hometeam']).
Bear in mind this will create upto 3 rows for each call, if you want to have a row like scores (hometeam, awayteam, result) you'll need to construct your query differently (i.e. a single query not 3 seperate ones).