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 succesfully
Notice: Undefined variable: sql in C:\xampp\htdocs\Syokimaufc\addplayer.php on line 35
Error: Query was empty" How can i solve this?
HTML form
<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 script
<?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"]["iname"]);
$imageData = mysql_real_escape(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["iname"]);
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());
}
in your form try adding an attribute:
<form enctype="multipart/form-data">
......
..
</form>
Have you tried it with the name property in the submit ?, it seems that is not going to "if"
<input type="submit" name="submit" value="submit"/>
just check following steps:
In html file, a form with image upload should be set with enctype="multipart/form-data"
e.g. <form enctype="multipart/form-data>
In PHP script
$_FILES["image"]["iname"] is wrong.
$_FILES["image"]["name"] should be the right one.
Related
This is for an assignment, so the code is based on how the learning resources are presented. I have a plant database that I have to make changes to, and then update plantID no.2. I have created the form which is then populated with plantID 2 info, but when I click the Update button after making changes, it wipes all the info for that entry in the database. I'm not sure where I have gone wrong. Any help would be awesome.
<?php
// MySQL Database Connect
require_once("connect.php");
// read the values from the form and store in variables
$botanicName = $_POST['bot_name'];
$commonName = $_POST['comm_name'];
$plantDescription = $_POST['pl_desc'];
$commonUse = $_POST['comm_use'];
$maxHeight = $_POST['m_height'];
$maxWidth = $_POST['m_width'];
$popular = $_POST['pop'];
// escape variables for security
$botanicName = mysqli_real_escape_string($conn, $bot_name);
$commonName = mysqli_real_escape_string($conn, $comm_name);
$plantDescription = mysqli_real_escape_string($conn, $pl_desc);
$commonUse = mysqli_real_escape_string($conn, $comm_use);
$maxHeight = mysqli_real_escape_string($conn, $m_height);
$maxWidth = mysqli_real_escape_string($conn, $m_width);
$popular = mysqli_real_escape_string($conn, $pop);
// create the UPDATE query
$query="UPDATE plant SET botanicName='$botanicName', commonName='$commonName', plantDescription='$plantDescription', commonUse='$commonUse', maxHeight='$maxHeight', maxWidth='$maxWidth', popular='$popular' WHERE plantID='2'";
//execute the query
$results = mysqli_query($conn, $query );
// check for errors
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
exit;
}
else {
// Redirect the browser window back to the make_changes page if there are no errors
header("location: ../make_changes.html");
}
?>
<h2>Edit a Plant</h2>
<?php
// run a select query to return the existing data for the record
$query = "SELECT * FROM plant WHERE plantID='2'";
$results = mysqli_query($conn, $query );
// capture any errors
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
}
else {
// fetch and store the results for later use if no errors
while ($row = mysqli_fetch_array($results)) {
$bot_name = $row['botanicName'];
$comm_name = $row['commonName'];
$pl_desc = $row['plantDescription'];
$comm_use = $row['commonUse'];
$m_height = $row['maxHeight'];
$m_width = $row['maxWidth'];
$pop = $row['popular'];
}
}
?>
<form method="post" action="code/update_plant.php">
<p>Botanic Name: <input type="text" name="botanicName" value="<?=$bot_name?>" required></p>
<p>Common Name: <input type="text" name="commonName" value="<?=$comm_name?>"required></p>
<p>Plant Description: <input type="text" name="plantDescription" value="<?=$pl_desc?>" required></p>
<p>Common Use: <input type="text" name="commonUse" value="<?=$m_height?>" required></p>
<p>Max. Height (m): <input type="text" name="maxHeight" value="<?=$m_height?>" required></p>
<p>Max. Width (m): <input type="text" name="maxWidth" value="<?=$m_width?>" required></p>
<p>Popular? (Y/N): <input type="text" name="popular" value="<?=$pop?>"required></p>
<input type="submit" name="submit" value= "Update">
</form>
The parameters sent to $_POST have the name key in your input so your $_POST['bot_name'] for example is empty, the correct way to get that name is $_POST['botanicName'].
This will be your post parameters:
$botanicName = $_POST['botanicName'];
$commonName = $_POST['commonName'];
$plantDescription = $_POST['plantDescription'];
$commonUse = $_POST['commonUse'];
$maxHeight = $_POST['maxHeight'];
$maxWidth = $_POST['maxWidth'];
$popular = $_POST['popular'];
The names you use in the form have to exactly match the indexes you use in $_POST. You are using variables that are not defined.
// read the values from the form and store in variables
$botanicName = $_POST['botanicName'];
$commonName = $_POST['commonName'];
$plantDescription = $_POST['plantDescription'];
$commonUse = $_POST['commonUse'];
$maxHeight = $_POST['maxHeight'];
$maxWidth = $_POST['maxWidth'];
$popular = $_POST['popular'];
Fix the mysqli escape function calls:
// variable $bot_name does not exist therefore it results in a null value
$botanicName = mysqli_real_escape_string($conn, $bot_name); // bad
// Fixed
$botanicName = mysqli_real_escape_string($conn, $botanicName); // good
Make the form input names the same as $_POST
<form method="post" action="code/update_plant.php">
<p>Botanic Name: <input type="text" name="botanicName" value="<?=$botanicName?>" required></p>
<p>Common Name: <input type="text" name="commonName" value="<?=$botanicName?>"required></p>
<p>Plant Description: <input type="text" name="plantDescription" value="<?=$plantDescription?>" required></p>
<p>Common Use: <input type="text" name="commonUse" value="<?=$maxHeight?>" required></p>
<p>Max. Height (m): <input type="text" name="maxHeight" value="<?=$m_height?>" required></p>
<p>Max. Width (m): <input type="text" name="maxWidth" value="<?=$maxWidth?>" required></p>
<p>Popular? (Y/N): <input type="text" name="popular" value="<?=$popular?>"required></p>
<input type="submit" name="submit" value= "Update">
</form>
I needed to change the indexes in the $_POST (I was using undefined variables) and change them also in the mysqli escape functions.
I have a php file (let's call it first) that stores names in a database. I now have a different php file with a html/php form (let's call it second). How can I make the form (second) input names into my database using my inital php (first) file?
Below is my php form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<h2>PHP FORM for Process Form</h2>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
<input type="checkbox" name="activate" value="Activate">Activate
</form>
</body>
</html>
Below is 'php first':
$nameList = 'Obi One, Not Naw, Lent Over, Foo Bar';
$newerName = 'Green Sauce';
$nameList = newUse($newerName,$nameList);
$email = '#email.org';
$fullnames = explode(" ",$nameList);
function newUse($nep, $nameList){
if($nep == empty($nameSplit[0]) && empty($nameSplit[1]) || empty($newName)){
return "$nameList, $nep";
}
return $nameList;
}
/*I open the database here*/
foreach ($fullnames as $fullname){
$nameSplit = explode(" ", $fullname);
if ($nameList == empty($nameSplit[0]) || empty($nameList)){
echo 'No First Name Here Or No Name At All';
echo '<br>';
echo '<br>';
} elseif ($nameList == empty($nameSplit[1])){
echo 'No Last Name Here';
echo '<br>';
echo '<br>';
} else{
$firstName = $nameSplit[0];
$lastName = $nameSplit[1];
$emailUser = $nameSplit[0].$email;
echo 'First Name: ' . $firstName;
echo '<br>';
echo 'Last Name: ' . $lastName;
echo '<br>';
echo 'Email Address: ' . $firstName . $email;
echo '<br>';
echo '<br>';
}
$queryString = "INSERT INTO `project`.`user`
(`id`, `firstName`, `lastName`, `email`, `activated`, `date_created`)
VALUES
(NULL, '$firstName', '$lastName', '$emailUser', '0', NOW())";
$result = mysqli_query($conn, $queryString)
or die (mysqli_error($conn));
}
I'm new to php and I'm really at a lost here. I'm pretty sure I need to use POST but I don't really understand how. Please help me out. Thank You.
Everything I have googled has not helped me and some of the similar questions on this site have not either. I need help.
You seem to have problem only with how to post the values, So your HTML file:
<form method="post" action="processForm.php">
First Name: <input type="text" name="firstname">
Second Name: <input type="text" name="lastname">
<input type="submit" value="Submit">
</form>
Your PHP file:
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$name = $firstName ." ". $lastName;
//Code for adding the values to the database.
If you put your function at the top of your processForm.php above where it is called it could be
// I am assuming this comes from your database
$nameList = 'Obi One, Not Naw, Lent Over, Foo Bar';
$newerName = $_POST['names'];
$email = '#email.org';
function newUse($nep, $nameList){
$nameSplit = array();
$nameSplit = explode(" ", $nep);
if(!empty($nameSplit[0]) && !empty($nameSplit[1]){
return "$nameList, $nep";
}
return $nameList;
}
$nameList = newUse($newerName,$nameList);
// need to explode on comma into name pairs with spaces or there will be nothing to explode into $nameSplit later.
$fullnames = explode(',', $nameList);
It might be worth making two text boxes - one for firstname name="firstname" and one for second name name="secondname", then putting the two together as in
$newerName = $_POST['firstname'] . " " . $_POST['secondname'];
This would ensure that you would reduce the risk of people putting two spaces or something else unwanted separating their names that would make your explode(); fail.
$newerName = mysqli_real_escape_string($newerName);
Before you put it into the function will help eliminate some of the security problems but it is not infallible.
The HTML would be
<form method="post" action="processForm.php">
First Name: <input type="text" name="firstname" required /><br />
Second Name: <input type="text" name="secondname" required /><br />
<input type="submit" value="Create Users" /><br />
<input type="checkbox" name="activate" value="Activate" />Activate
</form>
You could give your checkbox a value of 1 and pick that up as $activate = intval($_POST['activate']); where the forcing to integer will have the effect of cleaning it up. You could then use that as a variable where you currently have '0' in your MySql.
Ok i have updated my Code, not getting any Errors but nothing is being updated on the mysql side nor on the PHP Front end.
I have even tried a Hard Coded Statment.
This section is at the Very top of my Php Viewer page..
<?php
/
/ IF RESQUEST IS EQUAL TO SUBMUIT
if (isset($_REQUEST['submit']))
{
$my_date = date("Y-m-d H:i:s");
$order = uniqid();
$FullName= $_REQUEST['fullname'];
//Take in full Name and Split it into first and last name.
list($fname, $lname ) = explode( ' ', $customerName, 2 );
$address = $_REQUEST['address'];
$emailAddress = $_REQUEST['emailAddress'];
$phoneNo = $_REQUEST['phoneNo'];
Below is my Sticky Forum which is getting the Information from the Database and putting it into the Text Fields
// STICKY FORM TO ALLOW USER TO UPDATE INFORMATION
if (isset($_REQUEST['up']))
{
$query_sticky = mysqli_query($connection,'SELECT * FROM orders WHERE id = "' . $_GET['id'] . '"');
if(! $query_sticky )
{
die('Could not get data: ' . mysqli_error($connection)); // Could not find Order_id show Error
}//end die error
else
(isset($_REQUEST['update']));
{
while($row = mysqli_fetch_array($query_sticky, MYSQLI_ASSOC))
{
$row['id'];
echo '<form action="" method="post">'
Name:';
echo'<input name="customerName" id="cname" type="text" required value="'.$row['firstname']. " " .$row['lastname']. '" />';
echo' <br/>
<br/>
Address:
<textarea name="address" id = "caddress" type="text" rows="5" cols="30" required value="'.$row['address'].'" ></textarea>
<br/>
<br/>
Email Address:
<input name="emailAddress" type="email" required value="'.$row['email']. '" />
<br/>
<br/>
<br/>
Phone Number:
<input name="phoneNo" id="phoneNumber" type="text" required value="'.$row['phone']. '" />
<br/>
<br/>
<button type="submit" name="update" value="update" >update</button
<div id="Submit">
</form>
<form action="order.php" method="delete">
</form>';
}//close if
}
} // Close While
here is my Update Section
if (isset($_REQUEST['update']))
{
$updateDB = "UPDATE orders SET student ='$_POST[student]',
firstname='John', lastname='wallace',
email = '$_POST[emailAddress]', address = '$_POST[address]',
phone = '$_POST[phoneNo]'
WHERE
order_id ='$_GET[order_id]'";
mysqli_query($connection, $updateDB);
}//end update..
}//end PHP
?>
You were mixing up single and double quotes in your UPDATE query string. Try this instead:
$updateDB = "UPDATE test
SET email = '".#$_POST[$emailAddress]."',
address = '".#$_POST[$address]."',
phone = '".#$_POST[$phoneNo]."'
WHERE id = '".$_GET['id']."'";
I have this code below to insert in my Admins table the data that I store when when I fills the fields.
The insert is working fine, but Im having two notices and I´m trying to solve this but Im not finding a good method.
Somebody there can give a little help?
the two notices Im having:
-> Undefined index: date in $insertAdmin->bindValue(':avatar', $f['avatar']);
-> Undefined index: date in $insertAdmin->bindValue(':date_register', $f['date']);
My code:
if(isset($_POST['sendForm']))
{
$f['name'] = $_POST['name'];
$f['email'] = $_POST['email'];
//$f['avatar'] = $_POST['avatar'];
$f['date'] = $_POST['date_register'];
if(in_array('',$f))
{
echo 'Please, fill all fields.';
}
else
{
if(!empty($_FILES['avatar']['tmp_name']))
{
$image = $_FILES['avatar'];
$tmp = $imagem['tmp_name'];
$folder = '../uploads/avatars/';
$ext = substr($image['name'],-3);
$name = md5(time()).'.'.$ext;
$f['avatar'] = $name;
uploadImage($tmp, $name, '200', $folder);
}
$insertAdmin = $pdo->prepare("INSERT INTO admin (name, email, avatar, date_register) VALUES (:name, :email, :avatar, :date_register)");
$insertAdmin->bindValue(':name', $f['name']);
$insertAdmin->bindValue(':email', $f['email']);
$insertAdmin->bindValue(':avatar', $f['avatar']);
$insertAdmin->bindValue(':date_register', $f['date']);
}
}
My form:
<form name="form" action="" method="post" enctype="multipart/form-data">
<label class="line">
<span class="data">Name:</span>
<input type="text" name="name" value="<?php if(isset($f['name'])) echo $f['name'] ; ?>" />
</label>
<label class="line">
<span class="data">Email:</span>
<input type="text" name="email" value="<?php if(isset($f['email'])) echo $f['email'] ; ?>" />
</label>
<label class="line">
<span class="data">Avatar:</span>
<input type="file" class="fileinput" name="avatar" size="60" />
</label>
<label class="line">
<span class="data">Date of register:</span>
<input type="text" name="date_register" id="date" value="<?php if(isset($f['date'])) echo $f['date']; else echo date('d/m/Y H:i:s');?>" />
</label>
<input type="submit" value="Register" name="sendForm"/>
</form>
I see no valid reason to have the $f variable, it just makes it confusing.
I would personaly use the POST directly
if(isset($_POST['sendForm']
isset($_POST['name'] &&
isset($_POST['email'] &&
isset($_POST['avatar'] &&
isset($_POST['date'] &&){
//Insert
}else{
//please fill out everything
}
then execute like this
$insertAdmin = $pdo->prepare("INSERT INTO admin (name, email, avatar, date_register) VALUES (:name, :email, :avatar, :date_register)");
$insertAdmin->bindValue(':name', $_POST['name']);
$insertAdmin->bindValue(':email', $_POST['email']);
$insertAdmin->bindValue(':avatar', $_POST['avatar']);
$insertAdmin->bindValue(':date_register', $_POST['date']);
//do not forget to execute
$insertAdmin->execute();
You have a spelling error:
$f['date'] = $_POST['data_register'];
Needs to be:
$f['date'] = $_POST['date_register'];
//----------------------^
Which explains why $f['date'] is undefined.
use below an check again.
if(isset($_POST['sendForm']))
{
$f['name'] = $_POST['name'];
$f['email'] = $_POST['email'];
$f['avatar'] = $_POST['avatar'];
$f['date'] = $_POST['date_register'];
if(in_array('',$f))
{
echo 'Please, fill all fields.';
}
else
{
if(!empty($_FILES['avatar']['tmp_name']))
{
$image = $_FILES['avatar'];
$tmp = $imagem['tmp_name'];
$folder = '../uploads/avatars/';
$ext = substr($image['name'],-3);
$name = md5(time()).'.'.$ext;
$f['avatar'] = $name;
uploadImage($tmp, $name, '200', $folder);
}
$insertAdmin = $pdo->prepare("INSERT INTO admin (name, email, avatar, date_register) VALUES (:name, :email, :avatar, :date_register)");
$insertAdmin->bindValue(':name', $f['name']);
$insertAdmin->bindValue(':email', $f['email']);
$insertAdmin->bindValue(':avatar', $f['avatar']);
$insertAdmin->bindValue(':date_register', $f['date']);
}
}
I need help. What seems to be the problem with our php codes? We can't seem to insert our data into our database. I'm just a beginner and I'm tasked to store multiple data into multiple arrays into our database. What we're actually doing is to enter a number (ex: 5) and 5 forms should show within that page. each form would consist of name address and tel phone number. after that we submit it to our database. We have already controlled hot many forms to show but we weren't able to store the data inserted. Can anyone help us please? Thank you.
form.php
<form method="POST" action="form.php">
<input type="text" name="waw" />
<input type="submit" />
<?php
$i=0;
while ($i<$_POST['waw'])
{
?>
</form>
<form method="POST" action="input.php">
<!-- Person #1 -->
<input type="text" name="username[]" />
<input type="text" name="phonenum[]" />
<input type="text" name="add[]" />
<?php
$i++;
}
?>
<input type="submit" />
</form>
input.php
<?php
$username="maizakath";
$password="12345";
$database="tryinsert";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die("<b>Unable to specified database</b>");
$sql_start = 'INSERT INTO `mytable` VALUES ';
$sql_array = array();
$queue_num = $_POST['waw'];
foreach ($_POST['username'] as $row=>$name)
{
$username = $name;
$phonenum = $_POST['phonenum'][$row];
$add = $_POST['add'][$row];
$sql_array[] = '(' . $username . ', ' . $phonenum . ', ' . $add . ')';
if (count($sql_array) >= $queue_num)
{
mysql_query($sql_start . implode(', ', $sql_array));
$sql_array = array();
}
}
if (count($sql_array) > 0)
{
mysql_query($sql_start . implode(', ', $sql_array))or die(mysql_error());
}
?>
I've modified your code to make it work:
form.php
<form method="POST" action="form.php">
<input type="text" name="waw" />
<input type="submit" />
</form>
<form method="POST" action="input.php">
<?php
$i=0;
while ($i<$_GET['waw'])
{
?>
<!-- Person #1 -->
<input type="text" name="username[]" />
<input type="text" name="phonenum[]" />
<input type="text" name="add[]" /><br />
<?php
$i++;
}
?>
<input type="submit" />
</form>
input.php
<?php
$username="maizakath";
$password="12345";
$database="tryinsert";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die("<b>Unable to specified database</b>");
$sql_start = 'INSERT INTO `mytable` VALUES ';
$sql_array = array();
$queue_num = $_POST['waw'];
foreach ($_POST['username'] as $row=>$name)
{
$username = $name;
$phonenum = $_POST['phonenum'][$row];
$add = $_POST['add'][$row];
$sql_array[] = '("' . $username . '", "'.$phonenum.'", "'.$add.'")';
if (count($sql_array) >= $queue_num) {
$query_single=$sql_start . implode(', ', $sql_array);
mysql_query($query_single);
$sql_array = array();
}
}
if (count($sql_array) > 0) {
$query = $sql_start . implode(', ', $sql_array);
mysql_query($query)or die(mysql_error());
}
?>
It works fine. I've just tested it on my local machine.
EDIT(Comments):
Usage of variable $queue_num in input.php is senseless, because this variable is available only in form.php script('wow' input placed in another form, which is submitted to file form.php, not input.php). So if (count($sql_array) >= $queue_num) block works wrong;
Check your config settings for the database connection(as I've wrote in comment, you have to define constant with name 'localhost' or enclose word localhost with quotes);
I've modified your form, because it had wrong structure;
I didn't understand the objective of creating first form in form.php.
You can modify this code to make it more appropriate for your case. But firsat of all try to use this one.
Note. Use var_dump() function to see your $_POST array during debugging to understand, what variables are available.
I Had tried its work fine but when inserting into database it will insert null value also if user did'nt filled up the whole field.
I have stored two arrays in one table at the same time. Hope this will help you.
<?php
$i = 0;
foreach($element_name as $element_names){
$element_value = $_POST['element_value'];
$element_names_insert = mysql_query("insert into wp_remote_fields
set
remote_fields = '".$element_names."',
remote_values = '".$element_value[$i]."'
");
$i++;
}
?>