PHP doesn't insert in database - php

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');";

Related

The submit(update) button return an empty value, causing the update function not working

Currently doing the address part in e-commerce website application. The address needs to be edited. I have included the SQL query and PHP code well, but still can't run. There is no error message prompt. Below is my part of the code:
As there are multiple addresses, each address has an edit and delete button. The edit button will do the editing work based on the address-id passed inside.
<?php
while($row = mysqli_fetch_array($address_result_query)) {
$address_id=$row['address_id'];
$_SESSION['address_id'] = $address_id;
echo "<td>
<a class='editbutton' href='editaddress.php?
address_id=".$address_id."'>Edit</a>
</td>";
?>
On the edit page, it will show the address data currently, and allow the user to modify it inside the text box. Below is the code to get the user data.
<form name="update_" method="post" action="editaddress.php" >
<?php
$address_id = $_SESSION['address_id'];
$result2 = mysqli_query($mysqli, "SELECT * FROM user_address WHERE address_id='$address_id'");
$row2=mysqli_fetch_assoc($result2);
if(isset($row2['address'])!=null){
$address = $row2['address'];
$state = $row2['state'];
$city = $row2['city'];
$postcode = $row2['postcode'];
$address_name = $row2['address_name'];
$address_phone = $row2['address_phone'];
}
?>
Code to show the data:
<div class="container_header">
<p>Edit Address</p>
<br>
</div>
<label>Recipient Name:</label>
<br>
<input type="text" size="50" class="address_name"name="address_name" value="<?php echo $address_name;?>">
<br><br>
<label>Recipient Phone:</label>
<br>
<input type="text" size="50" class="address_phone"name="address_phone" value="<?php echo $address_phone;?>">
<br><br>
<label>Recipient address:</label>
<br>
<input type="text" size="50" class="address"name="address" value="<?php echo $address;?>">
<br><br>
<input type="text" size="50" class="state"name="state" value="<?php echo $state;?>">
<br><br>
<input type="text" size="50" class="city"name="city" value="<?php echo $city;?>">
<br><br>
<input type="text" size="50" class="postcode"name="postcode" value="<?php echo $postcode;?>">
<br><br>
<input type="button" onclick="location.href='index.php';" name="add_address" value="Cancel" class="cancel">
<input type="submit" name="update_address" value="Update">
</form>
When user click on the update address, below PHP will run, but it's not. The code are inside the edit page, same location with above
if(isset($_POST['update_address']))
{
if(isset($_POST['address'])){
$address = $_POST['address'];
}else echo"address not get";
$address_id = $_POST['address_id'];
$state = $_POST['state'];
$city = $_POST['city'];
$postcode = $_POST['postcode'];
$address_name = $_POST['address_name'];
$address_phone = $_POST['address_phone'];
$myquery = "UPDATE user_address SET
address='$address',
state='$state',
city='$city',
postcode='$postcode',
address_name='$address_name',
address_phone='$address_phone'
WHERE address_id='$address_id'";
$result = mysqli_query($mysqli,$myquery)or die(mysqli_error($mysqli));
header("Location: ../profile/index.php");
}
?>
The issue is that you are trying to set the address_id with a Post variable that is not submitted with the form. So when the query is being constructed the id is not being specified and it fails.
eg.
UPDATE user_address
SET address='123 Test Road',
state='Test',
city='Test City',
postcode='1234',
address_name='John',
address_phone='123456789'
WHERE address_id='' -- See no ID
It's best practice to use prepared statements. You can read more about them here:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
I'll help you out by showing you how you would do this in your code.
Below is code that shows how to fix the problem and resolve sql injection issues:
First update your select statement to use a prepared statement like this:
<?php
$address_id = $_SESSION['address_id'];
//Prepare the query
$stmt = $mysqli->prepare("SELECT * FROM user_address WHERE address_id = ?");
//bind the parameters
$stmt->bind_param("i",$address_id); //the i is for integer
//execute the query
$stmt->execute();
$result = $stmt->get_result();
while($row2 = $result->fetch_assoc()) {
$address = $row2['address'];
$state = $row2['state'];
$city = $row2['city'];
$postcode = $row2['postcode'];
$address_name = $row2['address_name'];
$address_phone = $row2['address_phone'];
}
$stmt->close();
?>
Then fix the initial problem by using the $_SESSION['address_id'] instead of $_POST['address_id'] and convert your update statement toa prepared statement:
<?php
if(isset($_POST['update_address']))
{
if(isset($_POST['address'])){
$address = $_POST['address'];
}else echo"address not get";
//$address_id = $_POST['address_id']; // <----- This is the problem line
//update your code so the above line is like this:
$address_id = $_SESSION['address_id'];
$state = $_POST['state'];
$city = $_POST['city'];
$postcode = $_POST['postcode'];
$address_name = $_POST['address_name'];
$address_phone = $_POST['address_phone'];
$myquery = "UPDATE user_address SET
address= ?,
state= ?,
city= ?,
postcode=?,
address_name=?,
address_phone=?
WHERE address_id=?";
//Prepare the query
$stmt = $mysqli->prepare( $myquery );
//bind the parameters
$stmt->bind_param("ssssssi", $address, $state, $city,$postcode, $address_name,$address_phone, $address_id); // s means string & i means int
//execute the query
$stmt->execute();
$stmt->close();
header("Location: ../profile/index.php");
}
?>
Another good read is this website here:
https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

adding image to database html form

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

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."',
........";

Adding my form data to the database using PHP

Hi there I am struggling with getting my form to post its data to MySQL database.
I have a config file setup like this:
// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'cms';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
The form php page:
<?php
include("config_database.php")
?>
<?php
include("addproduct.php")
?>
<article>
<section class="Input">
<fieldset><legend><span> Add a product to the database </span></legend>
<form action="addproduct.php" method="post">
<label> product name: </label><input type="text" name="name"><br />
<label> product quantity: </label><input type="text" name="quantity"><br />
<label> product description: </label><input type="text" name="description"><br />
<label> product price: </label><input type="text" name="price"><br />
<input type="submit" class="reg">
</form>
then a "addproduct.php" to hopefully send the data to the database:
require_once ("config_database.php");
if (isset($_POST['name']) &&
!empty($_POST["name"]) &&
isset($_POST['quantity']) &&
!empty($_POST["quantity"]) &&
isset($_POST['description']) &&
!empty($_POST["description"]) &&
isset($_POST['price']) &&
!empty($_POST["price"]))
{
$name = get_post('name');
$quantity = get_post('quantity');
$description = get_post('description');
$price = get_post('price');
$query = "INSERT INTO products VALUES" .
"('', '$name', '$quantity', '$description', '$price')";
}
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
How do I get the data entered in my form into my database?
You try the insert query like this using mysqli.
$query = "INSERT INTO products VALUES (NULL, '$name','$quantity', '$description','$price')";
$mysqli->query($query);
and also use real escape string like this for mysqli.
$mysqli->real_escape_string($_POST[$var]);

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