Insert query not working in MySQL , PHP - php

Here is my code to insert data in MySQL as Back-end and PHP as front-end
Connection is established properly but insert query is not working neither it is showing any error as per the else conditions at the end after insert query
It is not reaching inside the $_POST['submit'] too.
<html>
<head></head>
<title></title>
<body>
<form type="post" name="addimage" enctype="multipart/form-data" >
Album Name<input type="text" name="albumname">
<input type="file" name="filesToUpload" id="filesToUpload" multiple=""/>
</p>
Client Name<input type="text" name="clientname">
<br>Location<input type="text" name="location">
<button type="submit" value="submit" name="submit" id="submit">Submit</button>
</body>
</form>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "apostrophe";
$con=mysqli_connect("localhost","root","","apostrophe");
mysqli_select_db($con,"apostrophe");
if(isset($_POST['submit']))
{
echo "reached";
$albumname=$_REQUEST['albumname'];
$images=$_REQUEST['filesToUpload'];
$client=$_REQUEST['clientname'];
$loc=$_REQUEST['loc'];
echo "reached submit";
$sql="INSERT INTO album(albumname,images,clientname,location)VALUES('$albumname','$albumname','$client','$loc')";
echo "reached down";
if($con->query($sql)===TRUE)
{
echo "Success";
}
else
echo "Failed";
}
?>

The original code has quite a few errors in ( the form straddles the body, wrong declaration for form method, title outside the head etc ) and there is no attempt at handling the actual uploaded images. Hopefully the following ought to give you a headstart with getting the file handling piece completed - though no doubt I have missed something too '-)
<?php
$status='';
/* Might as well test that all necessary fields are included in form submission */
if( isset( $_POST['submit'], $_POST['albumname'], $_POST['clientname'], $_POST['location'] ) ){
/* only need to declare the db connection if the variables are set */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "apostrophe";
/* create the db conn */
$con=mysqli_connect("localhost","root","","apostrophe");
/* at least some basic filtering if you intend to place user submitted content directly in the sql */
$albumname=strip_tags( filter_input( INPUT_POST,'albumname',FILTER_SANITIZE_STRING ) );
$client=strip_tags( filter_input( INPUT_POST,'clientname',FILTER_SANITIZE_STRING ) );
$loc=strip_tags( filter_input( INPUT_POST,'location',FILTER_SANITIZE_STRING ) );
/* handle file uploads */
$fieldname='filesToUpload';
foreach( $_FILES[$fieldname]['name'] as $i => $name ) {
if( !empty( $_FILES[$fieldname]['tmp_name'][$i] ) ) {
$filename = $_FILES[$fieldname]['name'][$i];
$size = $_FILES[$fieldname]['size'][$i];
$type = $_FILES[$fieldname]['type'][$i];
$tmpfile = $_FILES[$fieldname]['tmp_name'][$i];
/* copy file to final destination - this is not complete!! */
$bytes=move_uploaded_file( $tmpfile, '/path/to/final/directory/'.$filename );
/* to debug uncomment below */
#echo $filename,$tmpfile,$size,$type;
}
}
/* prepare and execute sql */
$sql="INSERT INTO `album` ( `albumname`, `images`, `clientname`, `location` ) VALUES ( '$albumname', '$albumname', '$client', '$loc' )";
/* set status variable to be displayed under form */
$status=( $con->query( $sql )===TRUE ) ? "Success" : "Failed";
} else {
$status='bad foo';
$status=print_r( $_POST, true );
}
?>
<html>
<head>
<title>File upload and database inserts</title>
</head>
<body>
<form method="post" name="addimage" enctype="multipart/form-data" >
Album Name<input type="text" name="albumname">
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple=""/>
Client Name<input type="text" name="clientname">
<br>
Location<input type="text" name="location">
<button type="submit" value="submit" name="submit" id="submit">Submit</button>
</form><?php echo $status; ?>
</body>
</html>

Change your line :
<form type="post" name="addimage" enctype="multipart/form-data">
to
<form method="post" name="addimage" enctype="multipart/form-data">

Related

how to use if else statement in php/Html programming languages

I am new in PhP. i am trying to use if/else statement to request for (include 'user_index_Big_Data.php';) with different inputs.
when I run the code it will output all the .php forms. but i just want it to output just one form.
<html>
<head>
<LINK href="style.css" rel="stylesheet" type="text/css">
<title>Login</title>
</head>
<body>
<form action="" method="post">
<h1>Enter Key word to search</h1>
<p>Search <input type="text" name="username" placeholder='e.g. big data, Big Data'></p>
<p><input type="submit" name="submit" value="Search"></p>
</form>
</body>
</html>
<?php
$user = ("Big Data" || "big data" or "Big data" or "BIG DATA" or "big data analytics" or "BIG DATA ANALYTICS"
or "big data analysis");
$user1 = ("machine learning" || "MACHINE LEARNING" or "Machine Learning" or "Machine learning");
$user2 = ("Data center" || "Efficient Energy" or "Renewal Energy" or "Multi-Agents");
//$pass = "itsme";
if(isset($_POST["submit"])) {
if($_POST["username"] == $user )
include 'user_index_Big_Data.php';}
if(isset($_POST["submit"])) {
if($_POST["username"] == $user1 )
include 'user_index_machine_Learning.php';
}
if(isset($_POST["submit"])) {
if($_POST["username"] == $user3 )
include 'Energy.php';
}
else {
echo "Incorrect Key Word";
}
?>
please i want the code to output just one form. but it outputs all the forms. it echos all the results of the forms.
If you add the various key-words to arrays you can test for a match using in_array ~ though there is no need to include all possible uppercase/lowercase variants, just cast supplied user data to lowercase etc
<html>
<head>
<link href='style.css' rel='stylesheet' />
<title>Login</title>
</head>
<body>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['type'] ) ){
/* Process secondary form submission - do whatever needs to be done with secondary forms */
ob_clean();
$_POST['time']=time();
exit( json_encode( $_POST ) );
}
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit'], $_POST['username'] ) ){
/* Process primary form to select secondary form */
$file=false;
$user=array('big data','big data analytics');
$user1=array('machine learning');
$user2=array('data center','efficient energy','renewal energy','multi-agents');
$username=trim( strtolower( urldecode( $_POST['username'] ) ) );
if( in_array( $username, $user ) )$file='user_index_Big_Data.php';
if( in_array( $username, $user1 ) )$file='user_index_machine_Learning.php';
if( in_array( $username, $user2 ) )$file='Energy.php';
if( $file ){
if( file_exists( $file ) )require $file;
else printf( 'Unable to find file: "%s" to suit username "%s"', $file, $_POST['username'] );
} else {
printf( 'Incorrect Key Word: "%s"', $_POST['username'] );
}
}
?>
<form method='post'>
<h1>Enter Key word to search</h1>
<p>Search <input type='text' name='username' placeholder='e.g. big data, Big Data'></p>
<p><input type='submit' name='submit' value='Search'></p>
</form>
</body>
</html>
The other, secondarary, forms:
<?php
/* Big Data : user_index_Big_Data.php */
?>
<form name='big-data' method='post'>
<input type='text' name='type' value='big data' />
<input type='submit' />
</form>
<?php
/* machine learning : user_index_machine_Learning.php */
?>
<form name='machine-learning' method='post'>
<input type='text' name='type' value='machine learning' />
<input type='submit' />
</form>
<?php
/* Energy : energy.php */
?>
<form name='energy' method='post'>
<input type='text' name='type' value='Energy' />
<input type='submit' />
</form>

PHP Insert into MySQL Database doesn't work

I'm trying to input data into MySQL Database. I can log into database. However, whenever I run, the error "Error Querying Database 2" keeps appearing.
I'm suspecting my SQL Query having problems. However, I have checked my SQL query several times but I can't find any errors. (not yet)
Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<title>Create Events</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
}
?>
<body>
<?php
//define variables and set to empty values
$EventNameErr = $MembersAttending_Err = $EventDateErr = $LocationErr = $websiteErr = "";
$EventName = $MembersAttending = $EventDate = $Location = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["EventName"])) {
$EventNameErr = "A name for the event is required";
} else {
$EventName = test_input($_POST["EventName"]);
}
if (empty($_POST["MembersAttending"])) {
$MembersAttendingErr = "How many members are attending";
} else {
$MembersAttending = test_input($_POST["MembersAttending"]);
}
if (empty($_POST["EventDate"])) {
$EventDateErr = "The date of the event is required";
} else {
$EventDate = test_input($_POST["EventDate"]);
}
if (empty($_POST["Location"])) {
$LocationErr = "Location of the event is required";
} else {
$Location = test_input($_POST["Location"]);
}
//continues to target page if all validation is passed
if ( $EventNameErr ==""&& $MembersAttendingErr ==""&& $EventDateErr ==""&& $LocationErr == ""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$sql="SELECT * from Events WHERE EventName ='$EventName';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database 1");
$a=mysqli_num_rows($result);
if ($a>0){
$EventNameErr="Event Name already exists".$a;
} else {
$sql1="INSERT INTO Events VALUES(NULL,'$EventName','$MembersAttending','$EventDate','$Location');";
$result =mysqli_Query($dbc,$sql1) or die (" Error querying database 2");
mysqli_close();
header('Location: /EventCreated.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Event Creation </h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
EventName:
<input type="text" name="EventName" value="<?php echo $EventName;?>"/>
<span class="error">* <?php echo $EventNameErr;?></span>
<br/><br/>
Members:
<input type="text" name="MembersAttending" value="<?php echo $MembersAttending;?>"/>
<span class="error">* <?php echo $MembersAttendingErr;?></span>
<br/><br/>
Date:
<input type="text" name="EventDate" value="<?php echo $EventDate;?>"/>
<span class="error">* <?php echo $EventDateErr;?></span>
<br/><br/>
Location:
<input type="text" name="Location" value="<?php echo $Location;?>"/>
<span class="error">* <?php echo $LocationErr;?></span>
<br/><br/>
<input type="Reset" name="Reset" value="Reset">
<input type="submit" name="submit" value="Submit"/> 
</form>
</body>
</html>
I'm not sure what are the column name available in your table, but try with the following query,
I got the column name form your code, I'm not sure it's right or wrong. just try it.
$sql1="INSERT INTO Events (EventName,MembersAttending,EventDate,Location)
VALUES('$EventName','$MembersAttending','$EventDate','$Location');";

when i am edit files,Image file Not uploading his target path

I have developed small application with small form,Name and image.
When i am fill the form and click on submit button these form values are stored in database(Name and image path stored in database),and image stored in target folder.
Here is a problem,when i am click on form edit button,edited Name its successfully edited and stored in database.
But when i am browse a image file it's not storing his path into database and image into target folder.
It shows old image path and Image in DB and form.
Here is code.
Form.html
<html>
<form name="files" onsubmit="return formValidator()" action="update.php" method="POST" enctype="multipart/form-data">
<label class="form_label_name">Name<span class="red">*</span>:</label>
<input name="name" type="text" maxlength="32" class="form_input_name" id="form_name" required value="<?php {echo $row['name'];} ?>">
<label class="form_label_image">Grid Image:</label>
<img id="imagetd" class="gridimage" src="<?php {echo $row['thumbnailimage'];} ?>" onclick="getImagePathFromDialog()" />
<label>Click on the image to change the Image</label>
<input type="file" id="imageBrowser" name="imageBrowser" onchange="readURL(this);" style="visibility:hidden;" />
<input type="submit" value="Save" name="submit" class="editfile_save">
</html>
Edit Form:-
update.php:-
<?php
global $nodeid;
global $parentnodeid;
global $user;
global $file_type;
$file_type=$_GET['type'];
$userid=$user->uid;
if(isset($_POST['submit']))
{
$dbhost = 'localhost';
$dbuser = 'xxx';
$dbpass = 'yyy';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$sqlappidquery = "SELECT appid FROM app WHERE userid=$userid ";
$appidqueryrows = db_query($sqlappidquery, array());
foreach ($appidqueryrows as $appidrow) {
$app_id=$appidrow->appid;
}
if(! get_magic_quotes_gpc() )
{
$name = addslashes ($_POST['name']);
$summary = addslashes ($_POST['summary']);
$url= addslashes ($_POST['urlPath']);
}
else
{
$name = $_POST['name'];
$summary = $_POST['summary'];
$url = $_POST['urlPath'];
}
$target_path = "/sites/default/files/content_images/";
$imagepath=basename( $_FILES['imageBrowser']['name']);
$ext = explode("/", $_FILES['imageBrowser']['type']);
if($ext[0] == 'image')
{
if(empty($imagepath))
{
$target_path =$row['thumbnailimage'];
}
else
{
$target_path = $target_path . basename( $_FILES['imageBrowser']['name']);
}
move_uploaded_file($_FILES['imageBrowser']['tmp_name'], $target_path);
}
else
{
$target_path =$row['thumbnailimage'];
}
?>
Can any one help me on this problem.
<form name="files" onsubmit="return formValidator()" action="update.php" method="POST" enctype="multipart/form-data">
and change your select query like below
$sqlappidquery = "SELECT appid FROM app WHERE userid='".$userid."' ";
user form tag like this
I think u forgot to add enctype="multipart/formdata"
You need to add enctype="multipart/form-data"
and write update code
UPDATE appid SET image='$image' WHERE id='$id';

Keep text in text field after submit

I'm building a form, and I want that all the inserted values will be kept, in case of form submit failure. This is my code:
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value=""/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
I would like that name field keeps the inserted input text, after submit. I tried to do with php code in input value but doesn't work. Any ideas?
Solved. This is the solution that I was looking for.
I added in value tag of input the following:
<?php if (isset($_POST['name'])) echo $_POST['name']; ?>
Therefore input field would look like:
<input type="text" placeholder="Name" id="name" name="name" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"/>
Thanks for your responses, helped me.
<?php
$error = "";
$name = isset($_POST["name"])?$_POST["name"]:""; //Added condition
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
You can just echo $_POST['name'] in the value attribute of the input.
Make sure you check POST values to avoid XSS.
I also put up the update DB function, as you don't need to show the form to the user if the name in longer the 4 chars!
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['name'])){ //change name content only if the post value is set!
$name = filter_input (INPUT_POST, 'name', FILTER_SANITIZE_STRING); //filter value
}
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
} else {
// Update name in DB
// Redirect
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
};
?>
</body>
</html>
If you want to keep all values/inputs for further use you could achieve that with php session values.
Besides - you should use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']
Mars

File Not transferring to server

I have a webpage set up that allows for files to be uploaded, the url of the file is saved in the database that works fine, but the file its self is not getting transferred to the server. I am getting a confirmation of the file be saved and the is saving in the database.
Here is a copy of my code.
Any help would be great full.
// Start sessions
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Check to see if the form has been submitted
if (isset($_POST['submit']))
{
// Check to see all fields have been completed
$target = "../documents/memberDocuments/";
$target = $target . basename(str_replace(' ','_',$_FILES['documentsURL']['name']));
$documentsURL =(str_replace(' ','_',$_FILES['documentsURL']['name']));
$documentsDescription = $_POST['documentsDescription'];
$lessonID = $_POST['lessonID'];
if (!empty($documentsDescription) && !empty($documentsURL) && !empty($lessonID))
{
// Create an SQL query to add the comment
$sql = "INSERT INTO tblDocuments (documentsDescription, documentsURL, lessonID) VALUES ('$documentsDescription', '$documentsURL', '$lessonID')";
// Connect to the database
connect();
// Run the query and store the result in a variable
$result = mysql_query($sql) or die("Could not run query");
if(move_uploaded_file($_FILES['documentsURL']['tmp_name'], $target))
// Close connection to the database
mysql_close();
// Check if query was successful
if ($result)
{
$message = '<div class="success"><p>You have added a new lesson.</p><p>Please Click Here to view all modules.</p></div>';
}
else
{
$message = '<div class="error"><p>There was an error adding your record, please try again</p></div>';
}
}
else
{
$message = '<div class="error"><p>Please make sure you fill all fields in before submitting the form.</p></div>';
}
}
?>
<?php
if (isset($message))
{
echo $message;
}
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post" form enctype="multipart/form-data">
<fieldset>
<input type="text" name="documentsDescription" class="text" id="documentsDescription" placeholder="Enter The Lessons Number"></br></br>
<input type="file" name="documentsURL" class="text" id="documentsURL" placeholder="Enter The Lesson Description"></br></br>
<input type="text" name="lessonID" class="text" id="lessonID" placeholder="Enter The Module ID Number"></br></br>
<button type="submit" input type="submit" name="submit" id="submit" class="button iconLeft"><i class="email"></i> Submit</button>
</fieldset>
</form>

Categories