PHP not writing to first SQL field - php

Thank you guys, worked it out, turns out it was in the js a word wasn't spelled correctly, always something simple
This is my script to write data to my database on my local server, it currently only writes to 2 fields, not the alias one, have I done anything wrong? I've triple checked the names in both the html form and the database field.
<?php
// 1. Create connection to database
mysql_connect('localhost','root','') or die('Could not connect to mysql: <hr>'.mysql_error());
// 2. Select database
mysql_select_db("trialdb") or die('Could not connect to database:<hr>'.mysql_error());
// 3. Assign variables (after connection as required by escape string)
$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];
// 4. Insert data into table
mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')");
Echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close()
?>

First of all you should always check if the POST variables are being sent correctly:
if (
!isset($_POST['alias']) or
!isset($_POST['name']) or
!isset($_POST['email'])
) // something is wrong
Second, you don't want to inject user input directly into the sql query. You should perform some escaping first (or even better replace the mysql_* deprecated drivers with PDO or mysqli and just use prepared statements):
$alias = mysql_real_escape_string($_POST['alias']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
Third, you may want to check if the query performed correctly before printing a success message:
$res = mysql_query("INSERT INTO user_data (alias, name, email) VALUES ('$alias', '$name', '$email')");
echo ($res)
? 'Your information has been successfully added to the database.'
: 'Your information couldn't be added to the database';

you can try
<?php
$conn = mysql_connect('localhost','root','') or die('Could not connect to mysql: '.mysql_error());
mysql_select_db("trialdb", $conn) or die('Could not connect to database:'.mysql_error());
$alias = $_POST['alias'];
$name = $_POST['name'];
$email = $_POST['email'];
mysql_query("INSERT INTO user_data (`alias`, `name`, `email`) VALUES ('$alias', '$name', '$email')", $conn);
echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close();
?>

Related

How can I pass my user entered information to my database using php?

The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.
<!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
//<!-- post added information to database -->
if ($_POST['name']) {
if ($_POST['number']) {
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
} ?>
From looking at my code I believe the issue is with this line.
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
These hard coded entries are put into the database but i can't get the user entered data to go in.
Create variables for the $_POST values and add the vars for ease of code understanding:
$name = $_POST['name'];
$number = $_POST['number'];
$sql = "INSERT INTO hello (id, name, number) VALUES ('', $name, $number)";
One reason your code may not be working because you have the single quotes around the $_POST values, then you can also do what Jasbeer Rawal recommended.
UPDATE
Based on the kind comments... I would personally take a different approach to adding the data to your database, instead use prepared statements. I use MySQLi, but you can also use PDO.
Start by creating your connection:
<?php
define("HOST", "localhost");
define("USER", "");
define("PASSWORD", "");
define("DATABASE", "");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then when the user submits the form handle it:
if(isset($_POST['submit']
{
$name = $_POST['name'];
$number = $_POST['number'];
if ($stmt = $mysqli->prepare("INSERT hello (name, number) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $name, $number);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: Could not prepare SQL statement.";
}
}
This will add $name and $number and your ID role has to be a primary role and set to auto_increment. IDs will be automatically generated.
You're about to go down a slippery slope using mysqli. I'd recommend trying to learn to use PDO for making queries. Right now, someone could easily put SQL into the name POST data and actually do damage to your database.
Anyways, your problem at hand, you have a missing bracket and one issue:
VALUES ('', '$_POST['name']', '$_POST['number'')";
It won't work as intended with nested single quotes.
VALUES ('', '$_POST[name]', '$_POST[number]')";
Remove single quotes from $_POST['name'] and $_POST['number'] as below
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', $_POST['name'], $_POST['number'])";
Your insert code be like this
$sql = "INSERT INTO hello (id, name, number)
VALUES ('','{$_POST['name']}', '{$_POST['number']}')";
Then your value will be in database
If field id is primary key and auto increment then your insert statement should be like
Try this:
$sql = "INSERT INTO hello ( name, number)
VALUES ('{$_POST['name']}', '{$_POST['number']}')";

MySQL - PHP form to insert values into table?

I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. 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.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);

Flash as3 to PHP file not inserting data into mysql

I cannot find any syntax errors for the life of me so I don't understand why the data is not being inserted into my database. When I run the script in my browser with text instead of variables and no if statement I get a successful connection but It doesn't insert the data into mysql. Its driving me nuts! Thanks in advance.
PHP:
<?php
// Establish secure connection
$link = mysql_connect('myserver', 'myuser', 'mypass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(events_60);
if ($_POST['requester'] == "NewSale") {
$FirstName = $_POST['First_Name'];
$LastName = $_POST['Last_Name'];
$Birthday = $_POST['UserBirthday'];
$PhoneNumber = $_POST['PhoneNo'];
$Email = $_POST['UserEmail'];
mysql_query($link, "INSERT INTO events_60 (LastName, FirstName, Birthday, Phone, email)
VALUES('$LastName', '$FirstName',' $Birthday', '$PhoneNumber', '$Email')")
or die ("SYSTEM FAILURE");
echo 'System Updated';
} // close first if for post
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// close mysql connection
mysql_close();
?>
Assuming all data is posting correctly to the webpage I think the error resides here:
mysql_select_db(events_60);
It should be:
mysql_select_db('events_60', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
First of all select_db query should be
mysql_select_db('events_60',$link);
Then second problem is in mysql_query. It should be like this:
mysql_query("INSERT INTO events_60 (LastName, FirstName, Birthday, Phone, email)
VALUES('$LastName', '$FirstName',' $Birthday', '$PhoneNumber', '$Email')",$link)
or die ("SYSTEM FAILURE");
$link identifier should come after query.
Hope that fixes it. :)

SQL Error: Column count doesn't match value count at row 1

I have made a registration form that was previously working fine, however after some changes in my code I have error "Error: Column count doesn't match value count at row 1"
<?php
$host = "localhost";
$user = "root";
$db_name= "login_stock";
$pass= "usbw";
$con = mysql_connect($host, $user, $pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("login_stock", $con);
$name=mysql_real_escape_string($_POST['name']); //This value has to be the same as in the HTML form file
$password=mysql_real_escape_string($_POST['password']); //This value has to be the same as in the HTML form file
$sql="INSERT INTO member_login (id,Name,Password, Allowance) VALUES (NULL,'$name','$password, 100000')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "The form data was successfully added to your database.";
mysql_close($con);
?>
id within the database is an auto incrementing int and a primary key. However the user is not required to enter their ID when they register.
What is considered the best way to fix this error!
Thanks in advanced!
Other than an erroneous ', you could just drop id from the column list:
INSERT INTO member_login (Name,Password, Allowance) VALUES ('$name','$password', 100000)
You should stop using mysql_ functions and use prepared statements to prevent against SQL injections.
INSERT INTO member_login (id,Name,Password, Allowance)
VALUES (NULL,'$name','$password, 100000');
...only has 3 values (the third being the string '$password, 100000'). What you mean is probably to quote the password only;
INSERT INTO member_login (id,Name,Password, Allowance)
VALUES (NULL,'$name','$password', 100000);

MySQL Table inserts empty records before data

I'm a beginner at this. Basically I have a form that has the correct names set up, and it sends the data to the MySQL table correctly, but it always inserts an additional 4 blank rows/ID's whenever I execute the form.
Here's the result every time: http://i.stack.imgur.com/bnx5D.png
I'm not sure whether if there's something wrong with the code or the setup itself, can anybody help?
PHP code:
<?php
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$member_company = $_POST['member_company'];
$member_address1 = $_POST['member_address1'];
$member_address2 = $_POST['member_address2'];
$member_city = $_POST['member_city'];
$member_country = $_POST['member_country'];
$member_post_code = $_POST['member_post_code'];
$member_phone = $_POST['member_phone'];
mysql_connect ("localhost", "username", "password") or die ('Error: ' . mysql_error());
mysql_select_db ("database");
$query="INSERT INTO Orders (ID, email, first_name, last_name, member_company, member_address1, member_address2, member_city, member_country, member_post_code, member_phone)
VALUES ('NULL', '".$email."', '".$first_name."', '".$last_name."', '".$member_company."', '".$member_address1."', '".$member_address2."', '".$member_city."', '".$member_country."', '".$member_post_code."', '".$member_phone."')";
mysql_query($query) or die ('Error updating database');
?>
The thing is that every time you do a request you save the data on the table.
You should check if it is a POST request
if(isset($_POST){
//Then the form has been submitted
}
This is running on every GET request also, that's why you get those empty records.

Categories