adding image to database html form - php

I am trying to add records into a database. Each record has a corresponding image. The records are getting inserted into the database but it is not working for the image. I am getting this error "connected successfully Notice: Undefined variable: sql in C:\xampp\htdocs\Syokimaufc\addplayer.php on line 35 Error: Query was empty" How can i solve this?
<form action="addplayer.php"method ="post" enctype="multipart/form- data">
<p> id: <input type="text" name="playerid"/></p>
<p> Name: <input type="text" name="name"/></p>
<p> Age: <input type="text" name="age"/></p>
<p> Position: <input type="text" name="position"/></p>
<p> Nationality: <input type="text" name="nationality"/></p>
<p> Photo: <input type="file" name="image"/></p>
<input type="submit" value="submit"/>
<form/>
<?php
require 'connection.php';
$id = filter_input(INPUT_POST, 'playerid');
$name = filter_input(INPUT_POST, 'name');
$age = filter_input(INPUT_POST, 'age');
$position = filter_input(INPUT_POST, 'position');
$nationality = filter_input(INPUT_POST, 'nationality');
$_id = mysql_real_escape_string( $id );
$_name = mysql_real_escape_string( $name );
$_age = mysql_real_escape_string( $age );
$_position = mysql_real_escape_string( $position );
$_nationality = mysql_real_escape_string( $nationality );
if (isset($_POST['submit']))
{
$imageName = mysql_real_escape_string($_FILES ["image"]["name"]);
$imageData = mysql_real_escape(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["name"]);
if (substr($imageType,0,5) == "image")
{
$sql = "INSERT INTO players ( playerid, name, age, position, nationality, iname, image ) VALUES ( '$_id', '$_name', '$_age', '$_position', '$_nationality', '$imageName', '$imageData' )";
}
else
{
echo "only images are allowed";
}
}
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}

Put:
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
Immediately after
$sql = "INSERT IN..."
The problem is that because you run the query outside of all your if checks, the query will be run even when there is no input data (eg: no form was submitted), and $sql will be non-existent in that case. Hence the "Undefined variable: sql" and the "Query was empty" errors

Related

Adding records to a database using a html form

Having trouble populating my database usning a html form. Once i run the code the webpage outputs "Completed successfully" but the record does not display. It seems like its entering null values for each of the fields because when i try to enter another record, i'm getting this error "connected successfully Error: Duplicate entry '0' for key 'PRIMARY'" How can i solve this?
<form action="addplayer.php"method "post"/>
<p> id: <input type="text" name="playerid"/></p>
<p> Name: <input type="text" name="name"/></p>
<p> Age: <input type="text" name="age"/></p>
<p> Position: <input type="text" name="position"/></p>
<p> Nationality: <input type="text" name="nationality"/></p>
<input type="submit" value="submit"/>
?php
require 'connection.php';
$id = filter_input(INPUT_POST, 'playerid');
$name = filter_input(INPUT_POST, 'name');
$age = filter_input(INPUT_POST, 'age');
$position = filter_input(INPUT_POST, 'position');
$nationality = filter_input(INPUT_POST, 'nationality');
$_id = mysql_real_escape_string( $id );
$_name = mysql_real_escape_string( $name );
$_age = mysql_real_escape_string( $age );
$_position = mysql_real_escape_string( $position );
$_nationality = mysql_real_escape_string( $nationality );
$sql = "INSERT INTO players ( playerid, name, age, position, nationality )
VALUES ( '$_id', '$_name', '$_age', '$_position', '$_nationality' )";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
You need to add id to the input:
<p> id: <input type="text" name="playerid" id="playerid"/></p>
collect the data like this:
$playerID = mysql_real_escape_string($_POST['playerid'])
$sql = "INSERT INTO players
SET
playerID = '".$playerID."',
........";

Row being added to MySQL database but no other data from the html form using PHP

The data from the form is not getting saved into the database but a row is being added, I am hosting with Go Daddy. It worked perfectly on my local but now live seems to be not working. Please find below the code I am using:
<?php
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$fName = mysql_real_escape_string($_POST['fName']);
$surname = mysql_real_escape_string($_POST['surname']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$tel = mysql_real_escape_string($_POST['tel']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$email = mysql_real_escape_string($_POST['email']);
$bool = true;
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db name", $con);
$sql="INSERT INTO customer (custNo, fName, surname, postcode, tel, mobile, email, timestamp)
VALUES (NULL, '$fName','$surname','$postcode', '$tel', '$mobile', '$email', 'CURRENT_TIMESTAMP')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
} else{
echo "Successfully Registered ";
}
}
mysql_close($con)
?>
and here is the html form
<form action="insert.php" method = "post">
<fieldset>
<legend>Register</legend>
<div class="col-md-4">
<label for='fName'>Enter name:</label>
<input type= "text" name = "fName" required="required" maxlength="50"/> <br/>
</div>
<div class="col-md-4">
<label for='surname'>Enter surname:</label>
<input type= "text" name="surname" maxlength="50" required="required"/> <br/>
</div>
<div class="col-md-4">
<label for='postcode'>Enter postcode:</label>
<input type= "text" name="postcode" maxlength="7"/> <br/>
</div>
<div class="col-md-4">
<label for='tel'>Enter home no:</label>
<input type= "text" name="tel" maxlength="50" /> <br/>
</div>
<div class="col-md-4">
<label for='mobile'>Enter mobile no:</label>
<input type= "text" name="mobile" maxlength="50"/> <br/>
</div>
<div class="col-md-4">
<label for='email'>Enter email * </label>
<input type= "text" name="email" required="required"/> <br/></br>
</div>
<input type="submit" value="Register"/>
</fieldset>
</form>
First :
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
If you didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
This means the query sent to MySQL would be:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password.
To your problem !
All your variables are empty due to this fact ...
A MySQL connection is required before using mysql_real_escape_string()
otherwise an error of level E_WARNING is generated, and FALSE is
returned.
put your mysql_real_escape_string() after connect.
$con = mysql_connect("localhost","username","password");
if (!$con) { ...}
mysql_select_db("db name", $con);
//-------------- next after connect not before !!! --------
$fName = mysql_real_escape_string($_POST['fName']);
[...]
$email = mysql_real_escape_string($_POST['email']);
$bool = true;
$sql="INSERT INTO customer (...) VALUES (...)";
It may be due to the varibales.
try changing the $sql line to this
$sql = "INSERT INTO customer (custNo, fName, surname, postcode, tel, mobile, email, timestamp) VALUES (NULL, '" . $fName . "', '" . $surname . "', '" . $postcode . "', '" . $tel . "', '". $mobile . "', '" . $email . "', 'CURRENT_TIMESTAMP')";

PHP Insert INTO Not Inserting Data

Below is my Html and php code both in separate files for my insert query it is trying to insert registration details but it keeps failing, any reasons where i am going wrong.
I have trying using different types of speech marks but it still doesnt work and the textbook i have shows this method. The database can log users in and check if user exists but can not insert data. Thanks.
<?php
include 'db.php';
session_start();
?>
<!DOCTYPE html>
<html>
<head>
</head>
<?php
include 'header.php';
?>
<div id="logincontent">
<div id="registerform" class="loginform-in">
<h1>Registration</h1>
<fieldset>
<form id="myForm" action="registerscript.php" method="POST">
Email: <input type="text" name="username"/><br />
Password: <input type="password" name="pass"/><br />
First Name: <input type="text" name="fname"/><br />
Last Name: <input type="text" name="lname"/><br />
Address 1: <input type="text" name="add1"/><br />
Address 2: <input type="text" name="add2"/><br />
Postcode: <input type="text" name="pcode"/><br />
Telephone: <input type="text" name="phone"/><br />
<button id="submit">Register</button>
</form>
<div id="ack"></div>
</fieldset>
</div>
</div>
</body>
</html>
PHP File
<?php
include('db.php');
$email = mysql_real_escape_string( $_POST["username"] );
$pass = mysql_real_escape_string( md5($_POST["pass"]) );
$firstname = mysql_real_escape_string( $_POST["fname"] );
$surname = mysql_real_escape_string( $_POST["lname"] );
$add1 = mysql_real_escape_string( $_POST["add1"] );
$add2 = mysql_real_escape_string( $_POST["add2"] );
$pcode = mysql_real_escape_string( $_POST["pcode"] );
$phone = mysql_real_escape_string( $_POST["phone"] );
if( empty($email) || empty($pass) )
{
echo "Email and Password are Mandatory";
exit();
}
$res = mysql_query("SELECT email FROM members WHERE email='$email'");
$row = mysql_fetch_row($res);
if( $row > 0 )
echo "The Email $email has already been taken. Click Forgot Password to Retrieve";
else
{
$sql = "INSERT INTO members (memberid, firstname, surname, address1, address2, postcode, telephone, email, password) VALUES (
'',
'$firstname',
'$surname',
'$add1',
'$add2',
'$pcode',
'$phone',
'$email'
'$pass')";
if( mysql_query($sql) )
echo "Registration Successfull";
else
echo "An Error Occured Please Try Again";
}
?>
You missed a comma here
'$phone',
'$email', //<-------------- Here
'$pass')";
Remove memberid from $sql = insert into ... this is probably an auto_increment type value in your mysql database.
BTW you are better off using mysqli or pdo instead of using mysql_. And with prepared statements you would limit the risk for SQL injection.
Add the following to find MySQL Error:
else
echo "An Error Occured Please Try Again";
echo mysql_errno($res) . mysql_error($res);

PHP doesn't insert in database

I'm working on a Joomla module. I'm trying to take input from a form and insert it into a database. Here's my "helper.php" code:
<?php
/** post form to db module **/
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
//--build the form------------>
?>
<form name="names" id="names" action="<?php echo JURI::current(); ?>" method="post">
<p><input type="text" name="fname" id="fname" value="" /></p>
<p><input type="text" name="lname" id="lname" value="" /></p>
<p><input id="submit" name="submit" type="submit" value="Submit Names" /></p>
</form>
<!-- //--END BUILD THE FORM--------| -->
<?
if( (isset($_POST['lname'])) || (isset($_POST['fname'])) ) {
//first name or last name set, continue-->
$lname = $_POST['lname'];
$fname = $_POST['fname'];
/* $data =new stdClass();
$data->id = NULL;
$data->firstname = $fname;
$data->lastname = $lname;*/
$db =& JFactory::getDBO();
$query = "INSERT INTO `#__names` (`fname`, `lname`)
VALUES ($fname, $lname);";
$db->setQuery( $query );
$db->query();
} else {
echo '<h4>One Field Is Required!</h4>';
}
?>
I can see the form, but when I submit the data it doesn't update the database table. I've checked the Apache error log but it doesn't contain any information about it. What am I missing?
For your query it should be more like this, the way you have it will not work in 2.5.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->insert($db->quoteName('#__names'))
->columns(array($db->quoteName('fname', 'lname')))
->values($db->quote($fname),$db->quote($lname));
$db->setQuery($query);
$db->execute();
Remove ; from query and add quotes to the strings $fname and $lname
$query = "INSERT INTO `#__names` (`fname`, `lname`)
VALUES ('".$fname."', '".$lname."')";
And OPTIONALLY you need to insert NULL if the fields are empty like
$lname = (trim($lname) != '') ? $lname : 'NULL';
$fname = (trim(fname) != '') ? $fname : 'NULL';
Try this:
$query = "INSERT INTO `#__names` (`fname`, `lname`)
VALUES ('$fname', '$lname');";

PHP SQL registration form

I am attempting a registration form that saves the data into a sql db. I'm not doing form validation just yet as what is most troubling me is getting this stuff onto sql. I'd appreciate any advice!!
I have a form.php file that should be doing the hard work. When I submit my form, at this point, I get a blank screen and nothing loads into the database.
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
$password = md5($_POST['password']);
$connection = msql_connect(localhost, USERNAME, PASSWORD);
$db = mysql_select_db(registration,$connection);
mysql_query("INSERT INTO userTable (fname,lname,password,email,cell,experience,ip) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')")
or die (mysql_error());
echo "Thank you for your registration";
?>
And I have an html file that contains this:
<form method = "post" action = "form.php">
<h2>User Information</h2>
<div><label>First Name:</label>
<input type = "text" name = "fname"></div>
<div><label>Last Name:</label>
<input type = "text" name = "lname"></div>
<div><label>Password:</label>
<input type = "password" name = "password"></div>
<div><label>Email:</label>
<input type="text" name="email"></div>
<div><label>Cellphone:</label>
<input type="text" name="cell"></div>
<input type="hidden" name="ip" value='<?php echo $IP ?>'/>
<h2>What Is Your Experience Mountain Biking?</h2>
<p><input type="radio" name="experience" value="n00b"
checked>n00b
<input type="radio" name="experience" value="intermediate">Intermediate
<input type="radio" name="experience" value="extreme">Extreme
</p>
<p><input type="submit" name="submit" value="Register"></p>
</form>
Finally, I have a sql database (I'm running xampp locally) called "registration"
The table I've created is called "userTable" and it contains 8 fields including ID (auto incrementing) and the 7 other values I've included up top. Any idea what the heck I'm doing wrong?
What is the problem?
1) The problem is that it does INSERT query each time you load this page - mean each time it inserts empty values. Why?
Simply because there's no condition that checks if all fields has been posted, so instead of:
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
You should check if $_POST super-global has some keys.
So before doing any queries - first of all check if $_POST isn't empty
<?php
//This means that user did submit the form
if ( !empty($_POST) ){
//all your stuff goes here
}
?>
<html>
.....
</html>
2) Are you sure you are in control of your code? Apparently not.
You MUST check if some function returned TRUE and then make following actions relying on it's one.
For example, are you sure that mysql_query("your sql query") was succeed at?
3) Enable error_reporting to E_ALL, so just put error_reporting(E_ALL) at the top of your page, like this:
<?php
error_reporting(E_ALL);
So that you can always debug your script "on fly"
4) You are doing everything to make this code hard to maintain, Why?
Look at this:
<?php
//Debug mode:
error_reporting(E_ALL);
//Sure you want to show some error if smth went wrong:
$errors = array();
/**
*
* #return TRUE if connection established
* FALSE on error
*/
function connect(){
$connection = mysql_connect(localhost, USERNAME, PASSWORD);
$db = mysql_select_db(registration,$connection);
if (!$connection || !$db ){
return false;
} else {
return true;
}
}
//So this code will run if user did submit the form:
if (!empty($_POST)){
//Connect sql server:
if ( !connect() ){
$errors[] = "Can't establish link to MySQL server";
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
//Why post ip? not smth like $_SERVER['REMOTE_ADDR']...
$ip = $_POST['ip'];
$password = md5($_POST['password']);
//No error at this point - means that it successfully connected to SQL server:
if ( empty($errors) ){
//let's prevent sql injection:
$fname = mysql_real_escape_string($fname);
//Please do this for all of them..
}
//Now we should try to INSERT the vals:
$query = "INSERT INTO `userTable` (`fname`,`lname`,`password`,`email`,`cell`,`experience`,`ip`) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')";
//So try it:
if ( !mysql_query($query) ){
//
//die (mysql_error());
$errors[] = "Can't insert the vals";
} else {
//Or on success:
print ("Thank you for your registration");
//or you can do redirect to some page, like this:
//header('location: /thanks.php');
}
}
?>
<form method="post">
<h2>User Information</h2>
<div><label>First Name:</label>
<input type = "text" name = "fname"></div>
<div><label>Last Name:</label>
<input type = "text" name = "lname"></div>
<div><label>Password:</label>
<input type = "password" name = "password"></div>
<div><label>Email:</label>
<input type="text" name="email"></div>
<div><label>Cellphone:</label>
<input type="text" name="cell"></div>
<input type="hidden" name="ip" value='<?php echo $IP ?>'/>
<h2>What Is Your Experience Mountain Biking?</h2>
<p><input type="radio" name="experience" value="n00b"
checked>n00b
<input type="radio" name="experience" value="intermediate">Intermediate
<input type="radio" name="experience" value="extreme">Extreme
</p>
<?php if ( !empty($errors) ) : ?>
<?php foreach($errors as $error): ?>
<p><b><?php echo $error; ?></b></p>
<?php endforeach; ?>
<?php endif; ?>
<p><input type="submit" name="submit" value="Register"></p>
</form>
Solved my own problem
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname);
$email = mysql_real_escape_string($email);
$password = md5($_POST['password']);
$servername="localhost";
$username="user";
$conn= mysql_connect($servername,$username, password)or die(mysql_error());
mysql_select_db("registration",$conn);
$sql="insert into userTable (fname,lname,password,email,cell,experience,ip) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
echo "Thank you for your registration to the ";
mysql_close($connection);
?>

Categories