I hope this isn't a repeat question. I have searched all over to find an answer to no avail.
I want to insert into a row of a table. It sounds simple enough, but if the table is empty, it will not work. I can't figure out why. As long as there is one row in the table, it works fine. Any help is appreciated. Thanks.
My code:
<?php
$fname = $_POST['fname'];
$mi = $_POST['mi'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$add1 = $_POST['add1'];
$add2 = $_POST['add2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$con = mysqli_connect("localhost","database_username","database_password","database");
$sql1 = "INSERT INTO employee (fname, mi, lname, phone, email, add1, add2, city, state, zip) VALUES ('$fname', '$mi', '$lname', '$phone', '$email', '$add1', '$add2', '$city', '$state', '$zip')";
mysqli_query($con,$sql1);
mysqli_close($con);
?>
Your code is correct but it may some times data have some special characters such as \ / ? etc. thus suggest you to change all variable of the code from
$fname = $_POST['fname'];
to
$fname = addslashes($_POST['fname']);
then try it it will be done
You are not escaping the values. If any value contains an apostrophe, your query will faile. Since they come from post you must use mysqli_real_escape_string.
use following execute to insert a row
mysqli_query($con,$sql1);
musqli_execute($sql1);
I made it work after many hours of trying everything I could think of to do... Ultimately, I ended up checking for an empty table first, and then re-creating the table if it was empty.
I'm not sure why this works, but this is my code... it's a bit inelegant, but I could find no better solution. I know that I have not escaped my values. I will later. For now, I simply wanted to solve this problem that I have been wracking my brain about for days.
<?php
$fname = $_POST['fname'];
$mi = $_POST['mi'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$add1 = $_POST['add1'];
$add2 = $_POST['add2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$con = mysqli_connect("localhost","username","password","database");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$sql = 'CREATE TABLE employee'
. ' ('
. ' fname text,'
. ' mi varchar(1),'
. ' lname text,'
. ' email varchar(100),'
. ' phone varchar(15)'
. ' add1 varchar(100),'
. ' add2 varchar(100),'
. ' city varchar(100),'
. ' state varchar(25)'
. ' zip varchar(10),'
. ' );';
$sql1 = "INSERT INTO employee (fname, mi, lname, phone, email, add1, add2, city, state, zip,) VALUES ('$fname', '$mi', '$lname', '$phone', '$email','$add1', '$add2', '$city', '$state', '$zip')";
$sql2 = "SELECT * FROM employee";
$sql3 = mysqli_query($con,"SELECT count(*) FROM employee");
if ($sql3 == FALSE) {
trigger_error(mysql_error()." in ".$sql3);
exit();
}
else
{
$result = mysqli_fetch_array($sql3);
}
if($result[0] != 0)
{
mysqli_query($con,$sql1);
}
else
{
mysqli_query($con,$sql);
mysqli_query($con,$sql1);
}
mysqli_close($con);
?>
if variable is a string use '".$fname."' foreach variable in query
Related
I am inserting some data through PHP in MySql database, but unfortunately i am getting this error:
Error: Column count doesn't match value count at row 1
From the following code:
<?php
if($_POST)
{
include_once('dbconn.php');
$profile_created_by = $_POST['profile_created_by'];
$name = $_POST['name'];
$gender = $_POST['gender'];
$dd = $_POST['dd'];
$mm = $_POST['mm'];
$yyyy = $_POST['yyyy'];
$dob = $dd.'-'.$mm.'-'.$yyyy;
$marital_status = $_POST['marital_status'];
$religion = $_POST['religion'];
$mother_tongue = $_POST['mother_tongue'];
$country = $_POST['country'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$password = $_POST['password'];
$sql="INSERT INTO user VALUES ('$profile_created_by', '$name', '$gender', '$dob', '$marital_status', '$religion', '$mother_tongue', '$country', '$mobile', '$email', '$password')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "Entered data successfully";
mysql_close($conn);
}
?>
Can anybody help me out with this error?
If you have more columns in user table which are not mentioned here (e.g ID), You have to specify which data is for which column.
$sql="INSERT INTO user (profile_created_by,name,gender,dob,marital_status,religion,mother_tongue,country,mobile,email,password) VALUES ('$profile_created_by', '$name', '$gender', '$dob', '$marital_status', '$religion', '$mother_tongue', '$country', '$mobile', '$email', '$password')";
You are getting this error bcoz number of columns in the table user doesn't match with number of values supplied. So try using this type of format:
INSERT INTO user(columnNames,...)
VALUES(respective_values,....);
II created a form for inserting a new company and also on this page it is the PHP script which insert the data into the database.
I don`t know where it is the mistake in this code.
<?php
if (isset($_POST['submit']))
{
// Form has been submitted.
$query = mysql_query("INSERT INTO companies (name, subdomain0, subdomain1, subdomain2,
position, country, city, district, contact, set_up_date, address, phone, area_phone_code, website, fax, email)
VALUES ('{$_POST['name']}', '{$_POST['domain']}', '{$_POST['subdomain1']}',
'{$_POST['subdomain2']}', '{$_POST['position']}', '{$_POST['country']}', '{$_POST['city']}',
'{$_POST['district']}', '{$_POST['contact']}', '{$_POST['setdate']}', '{$_POST['address']}', '{$_POST['phone']}',
'{$_POST['areacode']}, '{$_POST['website']}', '{$_POST['fax']}', '{$_POST['email']}')");
$result = mysql_query($query, $connection);
if (!$result) {
echo "The company was not created.";
} else {
echo "The company was successfully created.";
}
}
?>
rewrite your code and remove those {} from the variables like that
VALUES ('$_POST['name']','$_POST['domain']', '$_POST['subdomain1']',...
1- be sure to escape them before you send them to database .
2-dont use mysql , use pdo or mysqli
to escape them do like that:
$name = mysql_real_escape_string($_POST['name']) ;
and then pass it to ur query like that
VALUES ('$name', .... <-- same with other columns
EDIT-
Try this
if (isset($_POST['submit'])) { // Form has been submitted.
$name = mysql_real_escape_string($_POST['name']) ;
$subdomain0 = mysql_real_escape_string($_POST['subdomain0']) ;
$subdomain1 = mysql_real_escape_string($_POST['subdomain1']) ;
$subdomain2 = mysql_real_escape_string($_POST['subdomain2']) ;
$position = mysql_real_escape_string($_POST['position']) ;
$country = mysql_real_escape_string($_POST['country']) ;
$city = mysql_real_escape_string($_POST['city']) ;
$district = mysql_real_escape_string($_POST['district']) ;
$contact = mysql_real_escape_string($_POST['contact']) ;
$set_up_date = mysql_real_escape_string($_POST['setdate']) ;
$address = mysql_real_escape_string($_POST['address']) ;
$phone = mysql_real_escape_string($_POST['phone']) ;
$areacode = mysql_real_escape_string($_POST['areacode']) ;
$website = mysql_real_escape_string($_POST['website']) ;
$fax = mysql_real_escape_string($_POST['fax']) ;
$email = mysql_real_escape_string($_POST['email']) ;
$query = mysql_query("INSERT INTO companies (name, subdomain0, subdomain1, subdomain2,
position, country, city, district, contact, set_up_date, address, phone, area_phone_code, website, fax, email)
VALUES ('$_POST['name']', '$subdomain0', '$subdomain1',
'$subdomain2', '$position', '$country', '$city',
'$district', '$contact', '$set_up_date', '$address', '$phone',
'$areacode, '$website', '$fax', '$email')");
echo "The company was successfully created.";
else {
echo "The company was not created.";
}
}
?>
you have to be careful with sql injections. you can go through the link to know of other options to mysql_* functions, as it is deprecated.
also its always better to try to find out the error by using mysql_error function to print out the error. (check the link for alternatives as this too is getting deprecated)
INSERT INTO companies
SET name = $name,
subdomain0 = $domain,
subdomain1 = $doamin1
so on
I am having a tough time figuring out how to write an if function in my code. I am trying to prevent my PHP form from allowing duplicates being submitted to my MySQL database. I am wanting to prevent a submission based on the email address being inputted into my form. Can someone guide me in the right direction? Thanks.
<?php
$dbc = mysqli_connect('n/a', 'n/a', 'n/a', 'n/a')
or die('Error connecting to MySQL server.');
$store_name = $_POST['storename'];
$full_name = $_POST['fullname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$fax = $_POST['fax'];
$email = $_POST['email'];
$url = $_POST['url'];
$query = "INSERT INTO store_location (store_name, full_name, address, city, state, zip, phone, fax, email, url) VALUES ('$store_name', '$full_name', '$address', '$city', '$state', '$zip', '$phone', '$fax', '$email', '$url')";
mysqli_query($dbc, $query)
or die('Error querying database.');
echo 'New TeachPro store added.';
echo '<br/><br/>';
mysqli_close($dbc);
?>
You should use a unique key on the email column on your database table. Now, if you try to insert the same email address twice, the MySQL responds with an according error message. You may catch those error message and present a useful error message text to the user.
I used that approach for checking usernames:
try
{
/** #var $userInsertUpdateStmt PDOStatement */
$userInsertUpdateStmt->execute();
}
catch(PDOException $e)
{
if($e->errorInfo[1] == 1062)
{
/* username already used */
return User::ERR_USERNAME_ASSIGNED;
}
return User::ERR_SQL;
}
SELECT count(*) FORM ... WHERE store_name = ... OR full_name=...
If you have 0 rows as a result of this query, you're good to go.
Also, your query is vulnerable to SQL-injection (google that).
Have a simple registration form that is being linked to a php file in order to send the info to a database but everytime i try it the data isnt showing up in the phpMyAdmin database??
<?php
$name = $_POST['name'];
$address = $_POST['address'];
$number = $_POST['number'];
$email = $_POST['email'];
$details = $_POST['details'];
$user="root";
$password="secure";
$database="darrenweircharity";
mysql_connect("localhost",$user,$password);
#mysql_select_db($database) or die ("Unable to select database");
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('$name', '$address', '$number', '$email', '$details' NOW())";
mysql_query($query);
mysql_close();
?>
Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Try with:
$query = "INSERT INTO registrationdetails(name, address, number, email, details)".
"VALUES('" . $name . "', '" . $address . "', '" . $number . "', '" . $email . "', '" . $details . "');";
You have NOW() at the end of the query that shouldn't be there.
Also note that your code has an SQL injection vulnerability (see mysql_real_escape_string()), I suggest you to prepare queries via PDO.
protect from possible SQL injection:
$name = mysql_real_escape_string($name);
$address = mysql_real_escape_string($address);
$number = mysql_real_escape_string($number);
$email = mysql_real_escape_string($email);
$details = mysql_real_escape_string($details);
replace with:
$query = "
INSERT INTO registrationdetails (`name`, `address`, `number`, `email`, `details`)
VALUES ('$name', '$address', '$number', '$email', '$details')");
$query = "
INSERT INTO registrationdetails (name, address, number, email, details, date_time)
VALUES ('{$name}', '{$address}', '{$number}', '{$email}', '{$details}', NOW())
";
Replace the date_time with your column_name. And remember to escape all submitted values with mysql_real_escape_string before inserting them into the database.
So I've been wrestling with this issue all day. I can't seem to post anything into my table and I'm not sure why.
I've got a form built that has all the values that are being transferred for the _POST. Any pointers would be great.
elseif ($request == 'POST') {
include 'header_post.php'; include 'topmain.php';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$dlnum = $_POST['dlnum'];
$dob = $_POST['dob'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$hair = $_POST['hair'];
$eyes = $_POST['eyes'];
$ethnicity = $_POST['ethnicity'];
}
$query3 = "insert into ".$db_prefix."customer_det (fname, lname, dlnum, dob, address, city, state, zip, phone, height, weight, hair, eyes, ethnicity)
values ('".$fname."', '".$lname."', '".$dlnum."', '".$dob."', '".$address."', '".$city."', '".$state."',
'".$zip."', '".$phone."', '".$height."', '".$weight."', '".$hair."', '".$eyes."', '".$ethnicity."')";
Using MySQL connection in PHP:
mysql_connect('DB_HOST','DB_USER','DB_PASS');
#mysql_select_db('DB_NAME');
$query='insert into ...';
mysql_query($query);
But your query is prone to SQL injections, and you are advised to use MySQLi extension.
$mysql = new mysqli('DB_HOST', 'DB_USER', 'DB_PASS', 'DB_NAME');
$query = 'insert into customer_det (
fname,
lname,
dlnum,
.......
) values (?,?,?,....,?)';
$statement = $mysql->prepare($query);
$statement->bind_param('sss...', //How many ever fields are there, those many sssss. For Integer use i. s is for string fields. Example ssssisssi....
$fname,
$lname,
$dlnum,
.....);
$statement->execute();
$statement->close();
$mysql->close();
you should use mysql_query :
$query3 = mysql_query("insert..");
you should also add this before $fname = $_POST['fname']; to prevent the query at page load :
if(isset($_POST['fname'])){
$fname = $_POST['fname'];
....
$query3 = mysql_query("insert..");
}
You are not performing query
use $result=mysql_query($query3);
There must be a query called.
use mysql_query();
As mentioned above, any variable using user inputted text that is stored in a database should be contained within the mysql_real_escape_string() to prevent SQL Injection.