PHP to MySQL Code problems - php

I know there a lot of questions on MySQL and PHP but I can't seem to find an answer simple enough for me to understand what to do and why.
Here is my form script
<form name="tickets" action="tickets98829849.php" method="get">
First Name: <input type="text" name="firstname"><br>
Last Name: <input type="text" name="lastname"><br><br>
Number of Tickets: <input type="text" name="quant"><br><br>
First and Last Name of Date: <input type="text" name="date"><br>
Date a guest? <input type="checkbox" name="guest" value="Yes">Yes<br><br>
Amount paid per ticket: <br><br>
$<input type="text" name="amount" size="2"><br>
<br><input type="submit" value="Submit"></form>
and here is my PHP script
<?php
define('DB_NAME', 'ticketpurch');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpsswd');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
if (!$link) {
die('Could not connect: ' . mysqlerror());
}
$db_selectd = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysqlerror());
}
$value1 = $_POST['firstname']
$value2 = $_POST['lastname']
$value3 = $_POST['quant']
$value4 = $_POST['datename']
$value5 = $_POST['guest']
$value6 = $_POST['amount']
$sql = "INSERT INTO $table ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$result = mysql_query($sql)
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
>
When I use the form, the data does not get entered into the table. I do not get an error message. What is wrong with it for not letting me access the table and insert data? I am very new to php, so

Your form's submit method is get but you receive post method. Change it.

In form you mention method="get" change it to method="post"
It will work :)

Remove the $table from the statement. I'm assuming the correct table is ticketpurch, so all you did with $table was confuse the database. In addition, the other answers are also correct. Your form's method is "get," yet you're using $_POST to try to get the data. You should change the form to post, because get is incredibly insecure, especially if this involves purchases.
In addition, you're using deprecated functions like mysql_connect. Instead, use the PDO object. Instead of mysql_connect(), try this:
$table = "mytable";
$sql = new PDO;
$sql->__construct(DB_NAME, DB_USER, DB_PASS);
$stmnt = $sql->prepare("INSERT INTO ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$sql->execute($stmnt);
That will ensure that your statements are better secured against SQL injection.
Hope that helped.

Try Like this.
HTML CODE
<form name="tickets" action="tickets98829849.php" method="post">
First Name: <input type="text" name="firstname"><br>
Last Name: <input type="text" name="lastname"><br><br>
Number of Tickets: <input type="text" name="quant"><br><br>
First and Last Name of Date: <input type="text" name="date"><br>
Date a guest? <input type="checkbox" name="guest" value="Yes">Yes<br><br>
Amount paid per ticket: <br><br>
$<input type="text" name="amount" size="2"><br>
<br><input type="submit" value="Submit"></form>
tickets98829849.php code
<?php
define('DB_NAME', 'ticketpurch');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpsswd');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
if (!$link) {
die('Could not connect: ' . mysqlerror());
}
$db_selectd = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysqlerror());
}
$value1 = $_POST['firstname']
$value2 = $_POST['lastname']
$value3 = $_POST['quant']
$value4 = $_POST['datename']
$value5 = $_POST['guest']
$value6 = $_POST['amount']
$sql = "INSERT INTO $table ticketpurch (firstname, lastname, quant, datename, guest, amount) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$result = mysql_query($sql)
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
>
If you use method="get" in the form,then receive html values using $_GET['html element name'];.But for security purpose ,we generally use method="post" in html code and receive value in action page using $_POST[];.

Related

sending data from form to database not working (php, sql)

I'm making a simple registration form for a test website and for some reason it isn't sending the data to the database, and I don't get an visual error. I've searched around for a fix but haven't found any that work.
This is basically my form (I only copied the form part of the page):
<form action="includes/insert.php" method="post">
<h3>Username</h3>
<input type="text" name="username">
<br>
<br>
<h3>Email Address</h3>
<input type="email" name="email">
<br>
<br>
<h3>Password</h3>
<input type="password" name="password">
<br>
<br>
<br>
<input id="submit-btn" type="submit" name="submit" value="Submit">
</form>
As you can see everything is as its suppose to be.
and this is my insert.php
<?
define('DB_NAME', 'logindb');
define('DB_USER', 'root');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
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());
}
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "INSERT INTO `users` (`id`, `username`, `email`, `password`, `timestamp`) VALUES (NULL, '$username', '$email', '$password', CURRENT_TIMESTAMP)";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
Opening PHP tag is
<?php
Recent versions of PHP do not enable the short code syntax by default.
Use NOW() instead of CURRENT_TIMESTAMP.

Connecting HTML to MYSQL Through PHP [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm working on a website but I'm a little unsure how to proceed. I've read through some documentation but I think I'm missing something or looking into the wrong stuff. Basically, I have a website with a bunch of pages and a few pages that have forms. I'm trying to tackle my first form, register, which contains a register form. Here is the form that the user will fill out to register:
<form action = "register.php" method = "post">
<br><br>First Name:<br>
<input type="text" name="firstname">
<br>
Last Name:<br>
<input type="text" name="lastname">
<br>
Street Address:<br>
<input type="text" name="streetaddress"> <br>
City:<br>
<input type="text" name="city"> <br>
State:<br>
<input type="text" name="state"> <br>
Zip Code:<br>
<input type="text" name="zipcode"> <br>
Phone Number:<br>
<input type="text" name="phonenumber"> <br>
Email Address:<br>
<input type="text" name="emailaddress"> <br>
User Name:<br>
<input type="text" name="username"> <br>
Password:<br>
<input type="text" name="password"> <br>
<br>Would you like to receive emails about CSIT World Conference?<br>
<input type="radio" name="email" value="yes">Yes
<input type="radio" name="email" value="no">No
<br><br>Would you be interested in volunteering at CSIT World Conference??<br>
<input type="radio" name="help" value="yes">Yes
<input type="radio" name="help" value="no">No
<br><br>
<input type="submit" value="Submit">
</form>
I thought it should then send the data to register.php which looks like this.
define('DB_NAME', 'register');
define('DB_USER', 'root');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_NAME, DB_HOST, DB_USER, DB_PASSWORD);
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());
}
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$streetaddress = $_POST['streetaddress'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$phonenumber = $_POST['phonenumber'];
$emailaddress = $_POST['emailaddress'];
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "INSERT INTO register (firstname, lastname, streetaddress, city, state, zipcode, phonenumber, emailaddress, username, password) VALUES ('$firstname', '$lastname', '$streetaddress', '$city', '$state', '$zipcode', '$phonenumber', '$emailaddress', '$username', '$password')";
$result = mysql_query($sql);
mysql_close();
</script>
</html>
I also created an empty MYSQL database through phpmyadmin on XAMPP. Basically I'm trying to figure out if I'm on the right track. My understanding is that once I hit submit, it should populate the register.mysql table I created. However, nothing seems to be happening.
Also, here is my connect.php file
<html>
<head>
</head>
<body>
<?php
$con = mysql_connect("localhost","root","password");
if(!$con){
die("Cannot connect:".mysql_error());
}
mysql_close($con);
?>
</body>
</html>
Any help or direction would be greatly appreciated.
You shouldn't use the mysql_* functions because they are deprecated. It's better to try to learn PDO but for this example you can use mysqli_*. Also, check about hashing passwords. I hope you find the following code useful.
<?php
define('DB_NAME', 'register');
define('DB_USER', 'root');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_set_charset($link, 'utf8');
if (!$link) {
die("Database connection failed: " . mysqli_error($link));
}
//Use array to not repeat code
$post_vars = array('firstname', 'lastname', 'streetaddress', 'city', 'state', 'zipcode', 'phonenumber', 'emailaddress', 'username', 'password');
foreach($post_vars as $key) {
$$key = mysqli_real_escape_string($link, $_POST[$key]);
//For example now there is a variable $firstname that you can use
}
$sql = "INSERT INTO user (firstname, lastname, streetaddress, city, state, zipcode, phonenumber, emailaddress, username, password) VALUES ('$firstname', '$lastname', '$streetaddress', '$city', '$state', '$zipcode', '$phonenumber', '$emailaddress', '$username', '$password');";
$result = mysqli_query($link, $sql);
mysqli_close($link);
?>
Edit:
You can select your data like this (consider also trying the PDO code that the other answer has).
$query = "SELECT username, firstname, lastname FROM user;";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row['username'].'<br />';
}
EDIT 2
The SQL for user table is the following. Edit it accordingly.
CREATE TABLE IF NOT EXISTS user (
id int unsigned not null auto_increment,
firstname varchar(40),
lastname varchar(40),
username varchar(40),
password varchar(40),
state varchar(40),
city varchar(40),
streetaddress varchar(40),
zipcode varchar(40),
phonenumber varchar(40),
emailaddress varchar(255),
email tinyint unsigned default 1,
help tinyint unsigned default 1,
time_created timestamp default CURRENT_TIMESTAMP,
primary key(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I would advise the same! use PDO and make sure you "PREPARE" your statements, I've re-written your data using PDO. By preparing our data we can prevent SQL injection which could have adverse affects on your data integrity as well as give unwanted users access to your tables.
<?php
// config
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "register";
$dbuser = "root";
$dbpass = "password";
// Connection Info
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// Write Query
$sql = "INSERT INTO books (firstname,lastname,streetaddress,city,state,zipcode,phonenumber,emailaddress,username,password) VALUES (firstname,:lastname,:streetaddress,:city,:state,:zipcode,:phonenumber,:emailaddress,:username,:password)";
// Prepare Statement
$q = $conn->prepare($sql);
$q->execute(array(':firstname'=>$firstname
':lastname'=>$lastname
':streetaddress'=>$streetaddress
':city'=>$city
':state'=>$state
':zipcode'=>$zipcode
':phonenumber'=>$phonenumber
':emailaddress'=>$emailaddress
':username'=>$username
':password'=>$password));
?>

Saving a webform to a database

I've been trying to learn PHP and have been given a simple task to help me.
I'm trying to get a user to complete a form which has their email address in it, then save it to a database.
Here's my code so far:
<html>
<body>
<form action="postemail.php" method="post"> Email Address: <input type="text" name="emailaddress" /> <input type="submit" />
</form>
</body>
</html>
<?php
$connection = mysql_connect("localhost","edwardHost","password");
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_database", $connection);
$sql="INSERT INTO Subscribers (EmailAddress) VALUES ('$_POST[emailaddress]')";
if (!mysql_query($sql,$connection)) {
die('Error: ' . mysql_error());
}
mysql_close($connection);
?>
Thanks in advance!
Change your query to this
One more thing i forget last time you are missing single quete around $_POST[emailaddress]. In your query
$sql="INSERT INTO Subscribers (EmailAddress) VALUES ('".$_POST['emailaddress']."')";
Dont use mysl function as the are deprciated
Learn mysqli_ function or PDO Or both
Check this link for mysql identifier http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
Try this example using PDO in your postemail.php
define('DB_TYPE', 'mysql');
define('DB_HOST', '127.0.0.1');
define('DB_NAME', 'dbname');
define('DB_USER', 'root');
define('DB_PASS', 'password');
try {
// create a new instance of a PDO connection
$db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if the connection fails, display an error message
echo 'ERROR: ' . $e->getMessage();
}
if(isset($_POST['emailaddress']) && !empty($_POST['emailaddress'])) {
$emailaddress = $_POST['emailaddress'];
$sql = 'INSERT INTO Subscribers (EmailAddress) VALUES (:emailaddress )';
$stmt = $db->prepare($sql);
$stmt->bindValue('emailaddress ', $emailaddress);
$stmt->execute();
}
After you have totaly filled in the form, it first needs to check if the submit button is clicked, then it has to send it to a database.
You also need to give you submit button a name=""
HTML code:
<html>
<body>
<form action="postemail.php" method="post">
Email Address: <input type="text" name="emailaddress" />
<input type="submit" name="submit" value="add to database" />
</form>
</body>
</html>
PHP code:
<?php
if(isset($_POST['submit'])){
$connection = mysqli_connect("localhost","edwardHost","password","my_database");
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
$email = $_POST['emailaddress'];
$sql = "INSERT INTO Subscribers (EmailAddress) VALUES ('$email')";
if (!mysqli_query($connection,$sql)) {
die('Error: ' . mysql_error());
}
mysql_close($connection);
}
?>
<html> <body>
<form action="postemail.php" method="post">
Email Address: <input type="text" name="emailaddress" />
<input type="submit" />
</form>
</body> </html>
<?php $connection = mysql_connect("localhost","username","password");
if (!$connection) { die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_database", $connection);
$sql="INSERT INTO Subscribers (EmailAddress) VALUES ('$_POST[emailaddress]')";
if (!mysql_query($sql,$connection)) { die('Error: ' . mysql_error()); }
mysql_close($connection);
?>

SQL Query doesn't get executed

I'm trying to make a very basic comment system in PHP.
The problem is that when I submit the form, the new row doesn't get inserted in my MySQL table.
This is my code (, could someone please check what's wrong?):
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')");
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>
I think your problem rests with the escaping, or rather the 'non-escaping' of the column names. Did you know that 'date' is a function name in mySQL?
Try putting all table and column names in backticks.
mysql_query("INSERT INTO `comments` (`name`, `message`, `date`) VALUES ('$name', '$message', '$date')");
Also, for further reference, posting the error message never hurts looking for the answer.
Other than that, I can't find anything particularly wrong with your query.
Edit: DUH! I missed something obvious.
Please execute 'mysql_select_db('name_of_database'); prior to the query.
Otherwise it won't know where to look for the table you're specifying.
For the sake of completeness (as Michael Besteck pointed out), it is necessary to execute 'mysql_real_escape_string' only AFTER the connection has been established.
That is, because the 'escape_string' relies on the encoding of the connection to determine which characters need to be escaped and how.
It is neccessary to first establish the database connection because the escape function is executed my mysql.
$con = mysql_connect("localhost","username","password");
$message = mysql_real_escape_string($m);
Run the script with this code and post mysql_error
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')") or die(mysql_error());
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>
UODATE>
The working code is follows:
<?php
$act = $_POST['act'];
if($act == 1) {
$m = $_POST['message'];
$m = strip_tags($m);
$message = mysql_real_escape_string($m);
$name = "Anonymous"; //Static username for demonstration purposes
$date = "2012-7-28"; //Static date for demonstration purposes
$con = mysql_connect("localhost","username","password");
mysql_select_db('databasename');
if (!$con){die('Could not connect: ' . mysql_error());}
mysql_query("INSERT INTO comments (name, message, date) VALUES ('$name', '$message', '$date')") or die(mysql_error());
mysql_close($con);
}
?>
<form action="comments.php" method="post">
<input type="text" name="message">
<input type="hidden" name="act" value="1">
<input type="submit" name="submit" value="Submit">
</form>

Form Redirect after Submit to PHP mySQL db

I need to redirect submissions so that users aren't taken to a blank screen.
Here's the code for my form::
<form action="giveaway_execute.php" method="post">
First Name:
<input type="text" name="firstname" /><br />
Last Name:
<input type="text" name="lastname" /><br />
etc...
...
...
<p><input type="submit" value="Submit"/>
</p>
</form>
and here's the php for 'giveaway_execute.php' which interacts with the mySQL db (everything submits; removed password and db name for security)::
<?php
define ( 'DB_NAME','xxxx');
define ( 'DB_USER','xxxx');
define ( 'DB_PASSWORD','xxxx');
define ( 'DB_HOST','localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
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['firstname'];
$value2 = $_POST['lastname'];
$value3 = $_POST['phone'];
$value4 = $_POST['street'];
$value5 = $_POST['city'];
$value6 = $_POST['state'];
$value7 = $_POST['zip'];
$value8 = $_POST['email'];
$value9 = $_POST['weddingdate'];
$sql = "INSERT INTO entrants (firstname, lastname, phone, street, city, state, zip, email, weddingdate) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
I've tried redirects on the PHP file but nothing is working. Any suggestions would be greatly appreciated.
Thank you.
You can just include another page after you're done with your database operations, or as suggested you can use a header call but be sure to use an absolute url.
Also worth noting your code is highly vulnerable to SQL injection, and it doesn't do any validation.
It's a good idea to use isset on your fields to avoid getting notices and SQL errors if fields aren't set.
Finally, it's recommended to use a library such as PDO or mysqli over the older mysql_* extension.
try
header('location:page2.php');
at the end of the file.
Replace page2.php with the actual page you want to send them to
// process.php
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
if(isset($_POST['value'])){
error_log(print_r($_POST,1),0);
$db->query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
header('Location: http://google.com');
exit();
}
else {
echo "$_POST is not set.";
}
// form.php
<form action="process.php" method="post">
<input type="text" name="value">
<input type="submit" id="submit-btn" value="Submit">
</form>
Try something simpler and build from there. Also read this: http://www.php.net/manual/en/pdo.prepared-statements.php

Categories