Beginner trouble with PHP & MySQL - php

I am very new to PHP & MySQL. Just designing websites for friends as a hobby, so any help is greatly appreciated. When I have a simple contact form on my page I keep getting error messages when submitting the information. Here is the PHP:
<?php
$con = mysql_connect("localhost","user","password");
if (!$con)) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database_name", $con);
$sql="INSERT INTO contact (first_name, last_name, email, phone, message)
VALUES
('$_POST[first_name]','$_POST[last_name]','$_POST[email]','$_POST[phone]','$_POST[message])";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
I put in my username & password where necessary, but I keep "localhost" there. Is this correct? I have hosting through webhostingpad. I also insert my database name above. Here is my HTML:
<!--Start of order form-->
<form id="contactform" method="POST" action="http://www.talephotography.com/insert.php">
<p><label>First Name:<br />
<input type="text" name="first_name" class="textfield" value="" />
</label></p>
<p><label>Last Name:<br />
<input type="text" name="last_name" class="textfield" value="" />
</label></p>
<p><label>Email: <br />
<input type="text" name="email" class="textfield" value="" />
</label></p>
<p><label>Phone: <br />
<input type="text" name="phone" class="textfield" value="" />
</label></p>
<p><label>Message: <br />
<textarea name="message" class="textarea" cols="45" rows="5"></textarea>
</label></p>
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
</form>
<!--End of order form-->
I can elaborate anywhere necessary.
Changed some of the code, it's only posting the email address to the database however.
mysql_select_db("databasename", $con);
$first = mysql_real_escape_string($_POST['first']);
$last = mysql_real_escape_string($_POST['last']);
$email = strip_tags(mysql_real_escape_string($_POST['email']));
$number = preg_replace('/[^0-9]/', '', $_POST['number']);
$number = (int) $number;
$sql="INSERT INTO contact (first, last, email, phone);
VALUES
('$first','$last','$email','$number')";
There's my code, however when I check my database the only info listed is the email address.

localhost is correct if the database server is on the same machine as the web server. When you set up the database it should have told you somewhere what you need to connect to.
That aside, escape your -----------ing inputs!!!!
Seriously, take those variables and wash them thoroughly with mysql_real_escape_string and then concatenate them into the query. You'll thank me later.

You have an extra ) in your if statement:
if (!$con)) {
should be
if (!$con) {

if (!$con)) it is wrong one extra ')' present here, remove ')' and then execute
for example
if (!$con){
//do something
}

Its query that is wrong, you have a ; that is in the middle of your query.
$sql="INSERT INTO contact (first, last, email, phone);
VALUES
('$first','$last','$email','$number')";
Notice it on the end of first line. Change this to:
$sql="INSERT INTO contact VALUES
('$first','$last','$email','$number')";

The problem is with your third line
$con = mysql_connect("localhost","user","password");
if (!$con)) {
die('Could not connect: ' . mysql_error());
}
there is an extra closing bracket ) in your third line. Remove it and then voilĂ !
hope this helps.

Related

PHP - INSERT Query failing, returns no error. Beginner

<form action="" method="post">
<input type="text" id="title" name="title" />
<input type="text" id="link" name="link" />
<input type="submit" value="Add resource" />
<?php
if(isset($_POST['title']) && $_POST['link']) {
$t = $_POST['title'];
$l = $_POST['link'];
$con = mysqli_connect("localhost","root","","rman");
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL:" . mysqli_connect_error());
}
mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('','$t','$l','')");
}
?>
</form>
How can this not work? I have removed every single part that might have caused this. Nothing is going in the database, no errors returning whatsoever.
For everyone wondering:
DB name: rman
Table name: tutorials
colums: id (INT11, Auto increment), title (Text), link (Text), section(INT11)
Am I being blind here? I'm sorry if thats the situation. Hope someone can see what I am doing wrong and help me out.
This should work.
<?php
if(isset($_POST['title']) && $_POST['link']) {
$t = $_POST['title'];
$l = $_POST['link'];
$con = mysqli_connect("localhost","root","","rman");
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL:" . mysqli_connect_error());
}
mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('', '$t', '$l', '1')");
}
?>
<form action="" method="post">
<input type="text" id="title" name="title" />
<input type="text" id="link" name="link" />
<input type="submit" name="submit" value="Add resource" />
</form>
use mysqli_error() to check error code, as well as don't insert blank id if it's AI
Thusly:
if (!mysqli_query($con, "INSERT INTO tutorials (id, title, link, section) VALUES ('','$t','$l','')"))
{
echo mysqli_error($con);
}

php won't insert into mysql. no errors

I create php and mysql database and table. This is my code:
<form action="proba.php" method="post" />
<p> ime: <input type="text" name="ime" /></p>
<p> prezime: <input type="text" name="prezime" /></p>
<p> datum rodjenja: <input type="text" name="godiste" /></p>
<p> jmbg: <input type="text" name="jmbg" /></p>
<p> adresa: <input type="text" name="adresa" /></p>
<p> email: <input type="text" name="email" /></p>
<p> telefon: <input type="text" name="telefon" /></p>
<p> datum: <input type="text" name="datum" /></p>
<input type="submit" value="insert" />
</form>
and here is my code to connect with mysql
<?php
$link = mysqli_connect("127.0.0.1", "root", "1511", "test");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
$db_selected = mysql_select_db ('test', $link);
if (!$db_selected) {
die('nedostupno ' . test . ' : ' . mysql_error ());
}
$values = $_POST['ime'];
$values2 = $_POST['prezime'];
$values3 = $_POST['godiste'];
$values4 = $_POST['jmbg'];
$values5 = $_POST['adresa'];
$values6 = $_POST['email'];
$values7 = $_POST['telefon'];
$values8 = $_POST['datum'];
$sql = "INSERT INTO users (ime, prezime, godiste, jmbg, adresa, emal, telefon, datum) VALUES ('values', 'values2', 'values3', 'values4', 'values5', 'values6', 'values7', 'values8')";
}
echo 'Connected successfully';
?>
And this is mysql:
You have made some few mistakes so that the query might not be inserting datas into the phpmyadmin database. The basic error you have made is in the insert query by not concatenating the values that you want in the VALUES section and the insert statement syntax will be like this.
Insert Syntax:
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.
So the basic form will be the same as you display in the question. I have added a name alone to the submit button and re-modified it.
HTML FORM:
<form action="proba.php" method="post" />
<p> ime: <input type="text" name="ime" /></p>
<p> prezime: <input type="text" name="prezime" /></p>
<p> datum rodjenja: <input type="text" name="godiste" /></p>
<p> jmbg: <input type="text" name="jmbg" /></p>
<p> adresa: <input type="text" name="adresa" /></p>
<p> email: <input type="text" name="email" /></p>
<p> telefon: <input type="text" name="telefon" /></p>
<p> datum: <input type="text" name="datum" /></p>
<input type="submit" name="save" value="insert" />
</form>
And your proba.php will look like this as i have coded below.
<?php
//Database connection Part of Mysqli
$host="localhost";
$user="root";
$password="1511";
$db="test";
$conn=new mysqli($host,$user,$pass,$db);
// Print Error if the connection is failed.
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Print Error if the DB is not selected.
if (!mysqli_select_db($conn, $db)) {
die("Uh oh, couldn't select database --> $db" . $conn->connect_error . ' >');
}
if(isset($_POST['save']))
{
$values = $_POST['ime'];
$values2 = $_POST['prezime'];
$values3 = $_POST['godiste'];
$values4 = $_POST['jmbg'];
$values5 = $_POST['adresa'];
$values6 = $_POST['email'];
$values7 = $_POST['telefon'];
$values8 = $_POST['datum'];
$sql = "INSERT INTO users (`ime`, `prezime`, `godiste`, `jmbg`, `adresa`, `emal`, `telefon`, `datum`) VALUES ('".$values."', '".$values2."', '".$values3."', '".$values4."', '".$values5."', '".$values6."', '".$values7."', '".$values8."')";
$query = mysqli_query($conn,$sql);
echo 'Inserted successfully';
}
?>
Note: You first put echo to the Insert Statement and then break the execution by putting the exit; and you copy the statement that is echoed and place it in SQL of the DB and then check whether any error occurs in insertion. If no error occurs remove the echo and delete the exit;
And you are inserting the data successfully. Hope so i would have given a clear explanation about the data not inserting into the database.
Do something like this:
$values = $_POST['ime'];
$values2 = $_POST['prezime'];
$values3 = $_POST['godiste'];
$values4 = $_POST['jmbg'];
$values5 = $_POST['adresa'];
$values6 = $_POST['email'];
$values7 = $_POST['telefon'];
$values8 = $_POST['datum'];
$sql = "INSERT INTO users (ime, prezime, godiste, jmbg, adresa, emal, telefon, datum) VALUES ('".$values."', '".$values2."', '".$values3."', '".$values4."', '".$values5."', '".$values6."', '".$values7."', '".$values8."')";
mysqli_query($link,$sql);
From the very first mistake.
You have added your success code in if condition where Server
connection object is gets fail to connect.
When you are using mysqli_connect for server connection then why
you are using mysql_connect.
Missing of query execution line. i.e. mysqli_query($link, $sql).

PHP does not work INSERT INTO method

I am trying to insert into customer table in eshop_db
When I run it, it does not have any error, but it did not store in mysql.
What it is problem in my code?
I don't understand really.
Please give some answer. Thanks.
--registerForm.php--
<form action="register.php" method="post">
<p>User ID: <input type="text" name="userId" size="30"/>*</p>
<p>Password: <input type="password" name="password" size="30"/>* </p>
<p>Retype Password: <input type="password" name="repassword" size="30"/>*</p>
<p>First Name: <input type="text" name="firstName" size="30"/>*</p>
<p>Last Name: <input type="text" name="lastName" size="30"/>*</p>
<p>Your Address (*):</p>
<p><textarea name="address" rows="5" cols="30"></textarea></p>
<p>Phone: <input type="text" name="phone" size="20"/>*</p>
<p>E-mail: <input type="text" name="email" size="21"/>*</p>
<p><input type="submit" value="Create Account"/></p>
</form>
--register.php--
<?php
require "sql_connection.php";
if(isset($_POST['submit']))
{
if($_POST["password"]==$_POST["repassword"])
{
mysql_query("insert into customer (userId, password, firstName, lastName, address, phone, email)
values ('$_POST[userId]','$_POST[password]','$_POST[firstName]','$_POST[lastName]','$_POST[addres]]','$_POST[phone]','$_POST[email]')")
or die(mysql_error());
}
}
?>
--sql_connection.php--
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "mypass";
$db_name = "eshop_db";
#mysql_connect("$db_host", "$db_username", "$db_pass", "$db_name") or die("connection is fail.");
#mysql_select_db("$db_name") or die("database does not exsist.");
echo "Successfully connected!!";
?>
Typo, correct this part here:
'$_POST[addres]]' // wrong
'$_POST[address]' // right
Try this:
<?php
require "sql_connection.php";
if(isset($_POST['submit']) && $_POST["password"] == $_POST["repassword"]) {
mysql_query(
'INSERT INTO `customer` (`userId`, `password`, `firstName`, `lastName`, `address`, `phone`, `email`)
VALUES ('.$_POST['userId'].', '.$_POST['password'].', '.$_POST['firstName'].', '.$_POST['lastName'].', '.$_POST['address'].', '.$_POST['phone'].', '.$_POST['email'].')'
) or die(mysql_error());
}
Finally, filter and validate your incoming data.
Well, besides the obviously bad idea to directly use the values in the POST array, your indexes need to be quoted. So, $_POST['address'], etc. Also, array values need to be escaped with curly-braces if you're trying to do string injection.

my php script enters blank info into mysql db!

When I try to enter data from a form I have made it adds a new entry as i can see from phpmyadmin but does not transfer other details across
I am using a simple form that collects 9 fileds post is to update.php. Here is what I have in update.php
<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];
mysql_connect ("localhost", "mydb_userid", "MYPASSWORD") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");
$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";
mysql_query($query) or die ('Error updating DB');
echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";
?>
Hope someone can help, searching the net seems to sugest something about global variables - but i dont know if i have control of that as its an hosted site.
this is the signup form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Candidate Registration</title>
</head>
<body>
<form medthod="post" action="update.php">
Real Name:<br />
<input type="text" name="realname" size="50" /><br />
Age:<br />
<input type="text" name="age" size="10" /><br />
Country:<br />
<input type="text" name="country" size="20" /><br />
In Game Name:<br />
<input type="text" name="gamename" size="30" /><br />
In Game Level:<br />
<input type="text" name="gamelevel" size="10" /><br />
In Game Item Level:<br />
<input type="text" name="itemlevel" size="10" /><br />
Class Played:<br />
<input type="text" name="class" size="30" /><br />
How long have you played wow?:<br />
<input type="text" name="played" size="10" /><br />
Please enter a brief statement of why you want to join:<br />
<input type="text" name="support" size="5000" /><br />
<br />
<input type="submit" value="Update DB" />
</form>
</body>
</html>
this is the update.php form
<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];
mysql_connect ("localhost", "mydb_daniel", "mypwd") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");
$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";
mysql_query($query) or die ('Error updating DB');
echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";
?>
I understand peoples concerns about sercurity, but please understand this only for me to mess around with and produce a basic signup form for my guild, i wont be requesting credit card details :)
Is your form method set to POST? - unless you have explicitly added this the variables will be within the $_GET superglobal so your variables would be like this:
$realname = $_GET['realname'];
If it is set to POST - please do a var_dump($_POST) at the top of your script and see if any variables are making it to your script.
Something else that i've seen before is caused when people are redirecting in a .htaccess from domain.com to www.domain.com and they post a script explicity to domain.com/script.php and the script then redirects to www.domain.com/script.php and this empties the POST.
EDIT
You have spelt method wrong in your form tag - if you update this then it should work as your misspelling will be causing the variables to be sent as GET vars.
You can fix your security issues in a basic way like this:
$realname = mysql_real_escape_string($_POST['realname']);
$age = mysql_real_escape_string($_POST['age']);
$country = mysql_real_escape_string($_POST['country']);
$gamename = mysql_real_escape_string($_POST['gamename']);
$gamelevel = mysql_real_escape_string($_POST['gamelevel']);
$itemlevel = mysql_real_escape_string($_POST['itemlevel']);
$class = mysql_real_escape_string($_POST['class']);
$played = mysql_real_escape_string($_POST['played']);
$support = mysql_real_escape_string($_POST['support']);
Whoa, slow down. You've not even escaped this data!
$realname = mysql_real_escape_string($_POST['realname']);
Or to escape it all:
$_POST = array_map('mysql_real_escape_string', $_POST);
Note the second solution isn't entirely reliable. Can produce some strange results. It is generally better to run these inputs through a function/class for validation and cleansing.
On your ghost issue, try this and note response after form submit (put right at top):
var_dump($_POST);
exit;
You spelled method attribute wrong in your query, that is why it isn't working.

Trying to write to a MySQL database with a PHP form

I'm trying to do a simple write to database with an HTML form, using PHP.
I've run the SQL query in the database and it works perfectly. However, using the form doesn't work. I'm not sure why. Any help? The user/pass/db name are all correct.
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
//also email it to us besides writing it into the database
mysql_close($con);
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/>
<br/>
<strong>Last name:</strong> <input type="text" name="lastName"/>
<br/>
<strong>Email:</strong> <input type="text" name="email"/> #####Put a javascript checker for valid emails, like name#site.com format
<br/>
<br/>
<strong>Idea:</strong>
<br/>
<textarea rows="10" cols="30" name="idea">
Hit us with your best shot.
</textarea>
<br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You forgot the "action = nameofyourpage.php" inside the form markup. And I would add a "or die (mysql_error())" at the end of your query to check the syntax of the request.
you've got a few errors in your script - please check the following
http://pastie.org/1056569
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
$sqlCmd = sprintf("INSERT INTO data (firstName, lastName, email, idea)
VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($_POST["firstName"]),
mysql_real_escape_string($_POST["lastName"]),
mysql_real_escape_string($_POST["email"]),
mysql_real_escape_string($_POST["idea"]));
mysql_query($sqlCmd);
mysql_close($con);
}
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/><br/>
<strong>Last name:</strong> <input type="text" name="lastName"/><br/>
<strong>Email:</strong> <input type="text" name="email"/>
<strong>Idea:</strong><br/>
<textarea rows="10" cols="30" name="idea">Hit us with your best shot.</textarea><br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You already have the answer to your question as to why it was not working, but please check this article about SQL injection attacks before putting this code into production.
you have error
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES
('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
Error = '$_POST['firstName']' you have chatter ' in post field
and you can change
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$idea = $_POST['idea'];
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('{$firstname}','{$lastname}', '{$email}', '{$idea}')");
or with mysql query
mysql_query("INSERT INTO data SET firstName='{$firstname}', lastName='{$lastname}',
email='{$email}', idea='{$idea}'");

Categories