I have a simple form for submitting some data into the MySQL DB. On local machine works just fine, but inside a Wordpress page template doesn't work anymore, without getting me any error. The form is inside a page "sitename.com/upload" and i get redirected after submit to the same page (as shown in the link bar), but with 404 page content. I tried without get_header();and get_footer();tags because I thought it may conflict with some variables from wp, but I got the same result.
Here is the code:
<?php function renderForm($name, $price, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
***** LONG HTML FORM IS HERE *****
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string($connection, htmlspecialchars($_POST['name']));
$price = mysqli_real_escape_string($connection, htmlspecialchars($_POST['price']));
$shortdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['shortdesc']));
$longdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['longdesc']));
$current_version = mysqli_real_escape_string($connection, htmlspecialchars($_POST['current-version']));
$content_rating = $_POST['contentrating'];
if(isset($_POST['category'])) {
$category = implode(",", $_POST['category']);
} else {
$category = "";
}
if(isset($_POST['platform'])) {
$platform = implode(",", $_POST['platform']);
} else {
$platform = "";
}
if(isset($_POST['devices'])) {
$devices = implode(",", $_POST['devices']);
} else {
$devices = "";
}
if(isset($_POST['gamemodes'])) {
$gamemodes = implode(",", $_POST['gamemodes']);
} else {
$gamemodes = "";
}
//FILE UPLOAD
$images = array();
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads/images";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==true){
move_uploaded_file($file_tmp,"uploads/images/".$file_name);
}else{ //rename the file if another one exist
$file_name = time()."-".$file_name;
$new_dir="uploads/images/".$file_name;
rename($file_tmp,$new_dir) ;
}
$images[] = $file_name;
}else{
print_r($errors);
}
}
if(empty($error)){
$imglinks = implode(" | ", $images);
}
}
//FILE UPLOAD END
// check to make sure both fields are entered
if ($name == '' || $price == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $price, $error);
}
else
{
$sql = "INSERT INTO vr_submitted_apps ". "(name, price, shortdesc, longdesc, crtvers, rating, category, platform, devices, gamemodes, images, dtime) ". "VALUES('$name','$price','$shortdesc','$longdesc','$current_version','$content_rating','$category','$platform','$devices','$gamemodes', '$imglinks', NOW())";
// save the data to the database
mysqli_query( $connection, $sql )
or die(mysql_error());
$itemId = mysqli_insert_id($connection);
setcookie("last-inserted-id", $itemId, time() + (86400 * 3), "/"); // 86400 = 1 day
// once saved, redirect back to the view page
header("Location: uploader.html");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
Problem solved: Wordpress has something important internal reserved for "name" parameter.
Related
I'm working on getting images from the database, which I've been saving as an url from the server it's been getting saved on.
There's this upload image section on the form, which is saving the images on a server and its url is getting saved in the database.
Here's the code:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= $target_file_cv;
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>
Here, I want to edit the file Name before it goes to the database. Like now it is saving as "/home/web/newsletter/uploads/pic.jpg" but I want it to be saved as "newsletter/uploads/pic.jpg".
I referred to a few questions here and got everything else working but just got stuck at hard coding the file's name here. Any help would be appreciated. TIA
$fileName = implode(array_slice(explode("/",$target_file_cv),3),"/");
Okay I got it:
Changed the code to:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= "newsletter/uploads/" . $_FILES['fileToUpload']['name'];
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>
I'm getting the error message when uploading a form in php.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
I am trying to have an Edit page that fetch the data selected by user and display them in a form. I manage to display the data from database and allow user to edit the data in the form. But my UPDATE query won't work in php. I tried echo the query and run it manual in xampp, it turns out to be ok and it was able to update manual in xampp but not in php. Can anyone help me with the codes? many thanks
this is my php coding
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_POST['btn-update']))
{
$ProdCode = mysql_real_escape_string($_POST['productCode']);
$ProdType = mysql_real_escape_string($_POST['productType']);
$ProdDes = mysql_real_escape_string($_POST['product_description']);
$ProdCol = mysql_real_escape_string($_POST['productColour']);
$ProdPrice = floatval($_POST['productPrice']);
$XSsize = mysql_real_escape_string($_POST['XSquantity']);
$Ssize = mysql_real_escape_string($_POST['Squantity']);
$Msize = mysql_real_escape_string($_POST['Mquantity']);
$Lsize = mysql_real_escape_string($_POST['Lquantity']);
$XLsize = mysql_real_escape_string($_POST['XLquantity']);
$XXLsize = mysql_real_escape_string($_POST['XXLquantity']);
if(isset($_FILES['productImg'])){
$file_name = $_FILES['productImg']['name'];
$file_size = $_FILES['productImg']['size'];
$file_tmp = $_FILES['productImg']['tmp_name'];
$file_type = $_FILES['productImg']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['productImg']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors="Please choose JPEG/PNG file.";
$errorTrigger =true;
}
if($file_size > 2097152) {
$errors='File size must be excately 2 MB';
$errorTrigger =true;
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
} }
$query = "UPDATE product SET product_code='$ProdCode', product_type='$ProdType' ,description='$ProdDes' ,colour='$ProdCol',price= '$ProdPrice',size_xs='$XSsize',size_s='$Ssize',size_m='$Msize',size_l='$Lsize',size_xl='$XLsize',size_xxl='$XXLsize' WHERE product_code='%". $ProdCode ."%'";
echo $query;
if(mysql_query($query))
{
echo "<script>
alert('Product Updated');
</script>";
}
else
{
echo mysql_error();
?>
<script>alert('Error while updating');</script>
<?php
}
}
?>
Hello everyone i'm able to display my record by passing an id by query string to another page, but i'm not able to update it, the problem is that when i click on update nothing happen, it return me a blank page, and there is no printed error, can someone help me please?
<?php
require 'db2.php';
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
$q = mysqli_query($dbc,"SELECT * FROM movie WHERE MovieID = '$id' ");
while($r=mysqli_fetch_array($q))
{
$title = $r["Title"];
$tag = $r["Tag"];
$year = $r["YEAR"];
$cast = $r["Cast"];
$comment = $r["Comment"];
$IDBM = $r["IMDB"];
}
}
At this stage, the code display every information i need , the stage below is where i'm having a problem, i'm not able to get the id against and make the update when click on update button
elseif (!empty($_POST) and !empty($_GET['id']) ) {
// keep track post values
$cast = $_POST['cast'];
$title = $_POST['title'];
$comment =$_POST['comment'];
$year = $_POST['year'];
$tag = $_POST['tags'];
$IDBM = $_POST['idbm'];
$cast = htmlspecialchars($cast);
$title = htmlspecialchars($title);
$comment = htmlspecialchars($comment);
// validate input
$valid = true;
if (empty($cast)) {
$castError = 'Please enter Cast';
$valid = false;
}
if (empty($title)) {
$titleError = 'Please enter Title';
$valid = false;
}
if (empty($comment)) {
$commentError = 'Please enter Comment';
$valid = false;
}
if ($valid) {
$id = $_REQUEST['id'];
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($dbc,"UPDATE movie SET Title='$title',Year = '$year',Cast='$cast',Cover='$actual_image_name',Tag='$tag',Comment='$comment',IMDB ='$IDBM' WHERE MovieID=".$id);
header ("Location: index.php");
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
}
First thing, when you get a blank page, check your error log. Or if you're lazy, add this at the begining of your file to get error messages.
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>
It's hard to say, but just looking at your code quickly, I see a problem with your mixup of $_GET and $_POST. From what I gather, since your SELECTworks, you send data in $_GET, and your UPDATE block is only executed if you have $_POST data.
Change your html <form method="get"> for <form method="post">
And change your select block to check if( !empty($_POST['id'])) {
I am bulding a small ajax chat site and am adding an image upload with msg functionality built in PHP, MySQL and jquery with ajax. My code currently will let you upload a message, I can get the image ready for upload and store URL for the database.
But I need to pass the variable to another if statement checking when the user submits a message.
I cannot seem to get it across and into my database.
Tryed global var, other stuff - think must be missing something. It is probably something obvious, excuse the code I am a graphic designer learning code!
$imageurl = "";
if (isset($_FILES["file"])) {
//properties of uploaded file
$name = $_FILES["file"] ["name"];
$type = $_FILES["file"] ["type"];
$size = $_FILES["file"] ["size"];
$temp = $_FILES["file"] ["tmp_name"];
$error = $_FILES["file"] ["error"];
if ($error > 0) {
die("Error uploaded file!");
}
else
{
if ($type == "video/avi" || $size > 2000000) {
?>
<br>
<p><?die("format is not allowed or size too big!");?></p>
<?
}
else
{
move_uploaded_file($temp, "msg_image/" . $name);
}
}
//store url for insertation
$imageurl = "msg_image/" . $name;
echo '<p>You added a ' . $name . ' to your message</p>';
return $imageurl;
}
/////need the var in here to store and update mysql database
if (isset($_POST['message'])) {
$tostore = $imageurl;
$username = protect($_POST['username']);
$message = protect($_POST['message']);
$time = time();
$sql = "INSERT INTO messages
(username, msgcontent, imageurl, msgtime)
VALUES ('$username', '$message', '$tostore', $time)";
$result = mysql_query($sql);
}
Your "return $imageurl" statement is stopping your script prematurely.
http://php.net/manual/en/function.return.php
i.e.
echo "hello";
return "world";
echo "!";
will only return
hello