Image uploaded but not stored - php

I am trying to store image name along with other data in the database but not being able to. nothing is inserted in the database. but the image is uploaded in the directory when i close the brace } before db config. but i got call to an undefined function upload() when i close the function brace } after inserting. here is the code:
$imagesub = isset( $_FILES['image'] );
if ( $imagesub )
{
$output=upload();
}
return $output;
function upload()
{
include_once "class.php";
$uploader = new Uploader( "image" );
$uploader->saveIn("images");
$fileUploaded = $uploader->save();
$db = new mysqli("localhost", "root","","learndb");
if ($db->connect_error) {
die("Connection failed this is the error: " . $db->connect_error);
}
$stmt = $db->prepare("INSERT INTO studentrecords (Name, email, Phone, school,dob,father,feereceived,due,image) VALUES (?,?,?,?,?,?,?,?,?)");
if($stmt)
{
$stmt->bind_param("ssisssiis",$name,$email,$phone,$school,$dob,$father,$feereceived,$due,$fileUploaded);
$stmt->execute();
$out="<center>information entered.</center>";
echo "$out";
}
else
{
$out="DATABASE ERROR!!!";
echo "$out";
}
return $out;
}
Here is the function save()
public function save(){
$folderIsWriteAble = is_writable( $this->destination );
if( $folderIsWriteAble ){
$name = "$this->destination/$this->filename";
if($succes = move_uploaded_file( $this->fileData, $name ))
{
return $name;
}
}
}

#Micky you have only 9 fields defined in your insert query but you are passing 10 parameters in ´bind_param()`.
$stmt->bind_param("ssisssiis",$name,$email,$phone,$school,$dob,$father,$feereceived,$due,$fileUploaded);
should be
$stmt->bind_param($name,$email,$phone,$school,$dob,$father,$feereceived,$due,$fileUploaded);
If it doesn’t resolve your problem then var_dump your $fileUploaded variable and make sure you have compatible datatype defined for column used for storing file name.

Related

How to hard code a file's name in the database while saving an image to the server in php?

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;
}
?>

PHP result row as an object not set

I have this PHP code in which I try to edit a row in the database
$sql="SELECT * FROM `event` where `EId`='".$_GET['EId']."'";
$res=$conn->query($sql);
$numrows=mysqli_num_rows($res);
if ($numrows>0)
{
$obj = mysqli_fetch_object($res);
}
if ($_REQUEST["mode"]=="save")
{
if ($_FILES['image']['name']!="")
{
del_img("event/",$obj->Picture);
$Picture=post_img($_FILES['image']['name'], $_FILES['image']['tmp_name'],"event");
}
else
$Picture = $obj->Picture;
$sqlu="update event set Picture='".$Picture."' where EId='".$_POST['EId']."'";
$conn->query($sqlu);
header("refresh:1; url=event_view.php");
die();
}
function post_img($fileName,$tempFile,$targetFolder)
{
if ($fileName!="")
{
if(!(is_dir($targetFolder)))
mkdir($targetFolder);
$counter=0;
$NewFileName=$fileName;
if(file_exists($targetFolder."/".$NewFileName))
{
do
{
$counter=$counter+1;
$NewFileName=$counter."".$fileName;
}
while(file_exists($targetFolder."/".$NewFileName));
}
$NewFileName=str_replace(",","-",$NewFileName);
$NewFileName=str_replace(" ","_",$NewFileName);
copy($tempFile, $targetFolder."/".$NewFileName);
return $NewFileName;
}
}
function del_img($targetfolder,$filname)
{
if (file_exists($targetfolder.$filname))
{
unlink($targetfolder.$filname);
}
}
When this is executed without uploading a new image it removes the present image and saves the row without any image. When uploading a new image it does not delete the current image.
I checked with isset and it tells me that the variable $obj->Picture is not set. I used this code in an older version of PHP and it still works but I can't seem to get it to work in the current one.
I am quite sure that the problem lies with $obj but I can't seem figure out what it is.
The HTML is just a form with file upload input and I have already set up a connection to the database with $conn being a new mysqli. The reason I am taking the entire row is because I am editing other stuff too
It feels like I am committing a fundamental mistake? What am I missing?
I'd bet there is some Problem with the num_rows_function.
Try to structure the code differently or at least make sure you have obj defined and initialised when the part of your code where the object is required is reached.
Do something like this for xample:
if ($_REQUEST["mode"]=="save" && isset($obj))
{
if (($_FILES['image']['name']!=""))
{
del_img("event/",$obj->Picture);
$Picture=post_img($_FILES['image']['name'], $_FILES['image']['tmp_name'],"event");
}
else
$Picture = $obj->Picture;
$sqlu="update event set Picture='".$Picture."' where EId='".$_POST['EId']."'";
(...)
Well, here's how I would fix this up. Your whole logic was messed up; now we have only the two conditions we need: is a valid EId sent, and is a file attached?
Database API is updated to something a tiny bit more modern, queries are prepared and parameterized for security, and we are properly sanitizing user input before using it to name files.
<?php
$conn = new PDO("mysql:host=localhost;dbname=database", "user", "password");
$stmt = $conn->prepare("SELECT Picture FROM event WHERE EId = ?");
$result = $stmt->execute([$_POST["EId"]]);
if ($obj = $stmt->fetch(\PDO::FETCH_OBJ)) {
if (!empty($_FILES["image"])) {
del_img("event/", $obj->Picture);
$Picture = post_img($_FILES['image'], "event");
$stmt = $conn->prepare("UPDATE event SET Picture = ? WHERE EId = ?");
$result = $stmt->execute([$Picture, $_POST["EId"]]);
}
header("Location: event_view.php");
die();
}
function post_img($file, $targetFolder)
{
if (!(is_dir($targetFolder))) {
mkdir($targetFolder);
}
$fileName = $file["name"];
$tempFile = $file["tmp_name"];
$NewFileName = str_replace([",", " "], ["-", "_"], basename($fileName));
$counter = 0;
while(file_exists($targetFolder . "/" . $NewFileName)) {
$counter += 1;
$NewFileName = $counter . $fileName;
}
move_uploaded_file($tempFile, $targetFolder . "/" . $NewFileName);
return $NewFileName;
}
function del_img($targetfolder,$filname)
{
if (file_exists($targetfolder . $filname)) {
unlink($targetfolder.$filname);
}
}

Lynda - PHP Beyond the Basics - Database error when uploading photo

I searched before writing this question but didn't think I would find a response because my issue is SO specific.
Anyway, I have been following the PHP Beyond the Basics course on Lynda.com by Kevin Skoglund and have run into a snag when it comes to uploading photos to the database (MySQL). This is my first real foray into OOP and have been brought to a stretching halt. I've been looking at my files for a over week trying my best to sort out the issue with no luck.
Oddly I have tried using the exercise files directly on my local machine and I'm getting the same error (with my information like database creds and directory names).
Basically my problem is that when I try to upload a photo it gets moved from the temp directory to the images directory but never makes its way to the database. I get the 'database query failed' message when it posts and the photograph table in mysql remains empty. I see where the error is coming from ( inside database.php confirm_query() ) but have no inclination as to what the issue could be. I know I am able to communicate with the database because just before moving onto creating the photograph class/table I was able to add users to the user table in the database.
Below are my files. Im adding the three that I believe relate to this issue but will zip the whole project up and upload it to dropbox as well. Any help/insight would be more than greatly appreciated!!
*please note that I have put the functions from the databaseObject into the photograph class
photo_upload.php:
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) {
redirect_to("login.php");
}
$max_file_size = 1048576; //expressed in bytes
// 10240 = 10kb
// 102400 = 100kb
//1048576 = 1mb
//10485760 = 1mb
$message = "";
if (isset($_POST['submit'])) {
$photo = new Photograph();
$photo->caption = $_POST['caption'];
$photo->attach_file($_FILES['file_upload']);
if ($photo->save()) {
//success
$message = "Photograph uploaded successfully";
} else {
//failure
$message = join("<br>", $photo->errors);
}
}
include_layout_template('admin_header.php');
?>
<h2>Photo Upload</h2>
<?php echo output_message($message); ?>
<form action="photo_upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>">
<p><input type="file" name="file_upload"></p>
<p>Caption: <input type="text" name="caption" value=""></p>
<input type="submit" name="submit" value="upload">
</form>
<?php include_layout_template('admin_footer.php'); ?>
Photograph.php:
<?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class Photograph extends DatabaseObject {
protected static $table_name="photographs";
protected static $db_fields=array('id', 'filename', 'type', 'size', 'caption');
public $id;
public $filename;
public $type;
public $size;
public $caption;
private $temp_path;
protected $upload_dir="images";
public $errors=array();
protected $upload_errors = array(
// http://www.php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
// Pass in $_FILE(['uploaded_file']) as an argument
public function attach_file($file) {
// Perform error checking on the form parameters
if(!$file || empty($file) || !is_array($file)) {
// error: nothing uploaded or wrong argument usage
$this->errors[] = "No file was uploaded.";
return false;
} elseif($file['error'] != 0) {
// error: report what PHP says went wrong
$this->errors[] = $this->upload_errors[$file['error']];
return false;
} else {
// Set object attributes to the form parameters.
$this->temp_path = $file['tmp_name'];
$this->filename = basename($file['name']);
$this->type = $file['type'];
$this->size = $file['size'];
// Don't worry about saving anything to the database yet.
return true;
}
}
public function save() {
// A new record won't have an id yet.
if(isset($this->id)) {
// Really just to update the caption
$this->update();
} else {
// Make sure there are no errors
// Can't save if there are pre-existing errors
if(!empty($this->errors)) { return false; }
// Make sure the caption is not too long for the DB
if(strlen($this->caption) > 255) {
$this->errors[] = "The caption can only be 255 characters long.";
return false;
}
// Can't save without filename and temp location
if(empty($this->filename) || empty($this->temp_path)) {
$this->errors[] = "The file location was not available.";
return false;
}
// Determine the target_path
$target_path = SITE_ROOT .DS. 'public' .DS. $this->upload_dir .DS. $this->filename;
// Make sure a file doesn't already exist in the target location
if(file_exists($target_path)) {
$this->errors[] = "The file {$this->filename} already exists.";
return false;
}
// Attempt to move the file
if(move_uploaded_file($this->temp_path, $target_path)) {
// Success
// Save a corresponding entry to the database
if($this->create()) {
// We are done with temp_path, the file isn't there anymore
unset($this->temp_path);
return true;
}
} else {
// File was not moved.
$this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
return false;
}
}
}
// Common Database Methods
public static function find_all() {
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE id={$id} LIMIT 1");
return !empty($result_array) ? array_shift($result_array) : false;
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record) {
// Could check that $record exists and is an array
$object = new self;
// Simple, long-form approach:
// $object->id = $record['id'];
// $object->username = $record['username'];
// $object->password = $record['password'];
// $object->first_name = $record['first_name'];
// $object->last_name = $record['last_name'];
// More dynamic, short-form approach:
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
// We don't care about the value, we just want to know if the key exists
// Will return true or false
return array_key_exists($attribute, $this->attributes());
}
protected function attributes() {
// return an array of attribute names and their values
$attributes = array();
foreach(self::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
protected function sanitized_attributes() {
global $database;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
// replaced with a custom save()
// public function save() {
// // A new record won't have an id yet.
// return isset($this->id) ? $this->update() : $this->create();
// }
public function create() {
global $database;
// Don't forget your SQL syntax and good habits:
// - INSERT INTO table (key, key) VALUES ('value', 'value')
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update() {
global $database;
// Don't forget your SQL syntax and good habits:
// - UPDATE table SET key='value', key='value' WHERE condition
// - single-quotes around all values
// - escape all values to prevent SQL injection
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id=". $database->escape_value($this->id);
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
public function delete() {
global $database;
// Don't forget your SQL syntax and good habits:
// - DELETE FROM table WHERE condition LIMIT 1
// - escape all values to prevent SQL injection
// - use LIMIT 1
$sql = "DELETE FROM ".self::$table_name;
$sql .= " WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
// NB: After deleting, the instance of User still
// exists, even though the database entry does not.
// This can be useful, as in:
// echo $user->first_name . " was deleted";
// but, for example, we can't call $user->update()
// after calling $user->delete().
}
}
?>
database.php:
<?php
require_once("config.php");
class MySQLDatabase {
//Step #1 open connection
private $connection;
function __construct() {//once you create an instance of this class it will automatically create the connection
$this->open_connection();
}
public function open_connection(){
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
//Test the connection
if(mysqli_connect_errno()){//use errno because error returns an empty string if succesful
die('Database connection failed: '. mysqli_connect_error().
'('.mysqli_connect_errno().')');
}
}
//Step #2 preform database query
public function query($sql){
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result){
if(!$result){ //this is a check to make sure the query worked
die('Database query failed');
}
}
public function escape_value($string){
$escaped_string = mysqli_real_escape_string($this->connection, $string);
return $escaped_string;
}
//database neutral functions
//this is our database adapter which is called for mysql
public function fetch_array($result_set){
return mysqli_fetch_array($result_set);
}
public function num_rows($result_set) {
return mysqli_num_rows($result_set);
}
public function insert_id(){
//get the last id inserted over the current connection
return mysqli_insert_id($this->connection);
}
public function affected_rows(){
return mysqli_affected_rows($this->connection);
}
//Step #4 close connection
public function close_connection() {
if(isset($this->connection)){
mysqli_close($this->connection);
unset($this->connection);
}
}
}
$database = new MySQLDatabase();
?>
https://www.dropbox.com/s/oqdi2dz2mbkuwzz/photo_gallery.zip?dl=0
After more digging around I have concluded that my problem was not with my code. There was an sql setting that would not allow me to enter and empty string sqlmode=STRICT_TRANS_TABLES. Thank you maxhb for pointing me in the right direction!!
What I did end up doing to solve this issue was create a my.conf file to change the default settings (im running mysql 5.7.9 on mac osx 10.11 btw). What was weird was that it only worked if I put this file in two locations they are .my.cnf and /etc/mysql/my.cnf with the following text:
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION

Can't record fields into database (php, SQL)

I'm trying to take a form that a user inputs from an HTML site and send the information to a SQL database. I am able to print out the variables after submission, so I know at the very least the variables are set properly. So I have to assume my code to send the content to the database is at fault here.
Here's the code:
//Taking variables from HTML input
if (isset($_POST['group'])) {
$group = $_POST['group'];
} else {
echo $error; return;
}
if (isset($_POST['game'])) {
$game = $_POST['game'];
} else {
echo $error; return;
}
if (isset($_POST['platform'])) {
$platform = $_POST['platform'];
} else {
echo $error; return;
}
if (isset($_POST['player'])) {
$player = $_POST['player'];
} else {
echo $error; return;
}
if (isset($_POST['play'])) {
$play = $_POST['play'];
} else {
echo $error; return;
}
if (isset($_POST['timezone'])) {
$timezone = $_POST['timezone'];
} else {
echo $error; return;
}
$error = 0;
//Retrieving Databse
try {
//userID and password is defined, just hiding it here
$dbh = new PDO("mysql:host=localhost;dbname=userID", "userID", "password");
} catch (Exception $ex) {
die("<p>($e->getMessage())</p></body></html>)");
}
//Inputting content into MySQL
$command = "INSERT INTO teams ( group, game, platform, player, play, timezone )
VALUES ( '$group','$game','$platform','$player','$play','$timezone')";
$stmt = $dbh -> prepare($command);
if ( ! $stmt->execute() ) {
$error = "<b>ERROR:</b> Could not record fields"; echo $error; return;
}
I'm not really sure where I've gone wrong, could be possible it's the tiniest thing or just something I've overlooked.
Thanks in advance for any help, guys!
This is how I did it for my Assignment:
Connecting to MySQL (notice that I dont have any mysql:host=):
$mysqli = new mysqli("localhost", "username", "pass", "database_name");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
Then in your code, when initializing variabels from POST, escape the strings. This will give you some protection against SQL-Injections:
$Name = $mysqli->real_escape_string($_POST["txtName"]);
$Street = $mysqli->real_escape_string($_POST["txtStreet"]);
$City = $mysqli->real_escape_string($_POST["txtCity"]);
Now, prepare a SQL code to insert your params:
$input = $mysqli->query("INSERT INTO customer (MembershipID, Name, Street, City, PostCode, Email, Password, DateJoin, Salt)
VALUES ('". $MembershipID."','".$Name."','".$Street."','". $City."','". $PostCode."','". $Email."','". $Password."','". $DateJoined."','". $Salt."')");
I hope it helps, Good Luck.

Insert User Data to Database with INSERT statement

From a user form: I am trying to insert the following data:
1) First Name 2) Last Name 3) Major 4) Graduation Year
I am able to connect to the database, and select the database I need--but I am unable to insert the data from the form. I am able to create records, but the data is not being saved to the database. Basically, right now I'm creating blank forms.
The variable $uInput holds the user data. I tried passing $uInput into the function doAction(), but I believe that is where the problem is. I'm trying to figure out how to pass the user data into the function doAction().
<?php
//Call function mainline
mainline();
// Declare the function mainline
function mainline() {
$uInput = getUserInput();
$connectDb = openConnect(); // Open Database Connection
selectDb($connectDb); // Select Database
doAction($uInput);
//closeConnect();
//display();
}
//Declare function getUserInput ------------------------------------------------------------------------------------
function getUserInput() {
echo "In the function getUserInput()" . "<br/>";
// Variables of User Input
$idnum = $_POST["idnum"]; // id (NOTE: auto increments in database)
$fname = $_POST["fname"]; // first name
$lname = $_POST["lname"]; // last name
$major = $_POST["major"]; // major
$year = $_POST["year"]; // year
$action = $_POST["action"]; // action (select, insert, update, delete)
$userInput = array($idnum, $fname, $lname, $major, $year, $action);
//echo "info from getUserInput: " . $action;
return $userInput;
}
function doAction($pUserInput) {
// if user selects INSERT from dropdown menu, then call function insert
//and pass $uInput
if ($pUserInput[5] == "ins") {
insert($uInput);
}
}
// Create a database connection --------------------------------------------------------
function openConnect() {
$connection = mysql_connect("localhost", "root_user", "password");
echo "Opened Connection!" . "<br/>";
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
return $connection;
}
// Select a database to ----------------------------------------------------------------
function selectDb($pConnectDb) {
$dbSelect = mysql_select_db("School", $pConnectDb);
if(!$dbSelect) {
die("Database selection failed: " . mysql_error());
} else {
echo "You are in the School database! <br/>";
}
}
// function insert ---------------------------------------------------------------------
function insert($pUInput) {
$sql="INSERT INTO tblStudents (first_name, last_name, major, year)
VALUES
('$pUInput[1]','$pUInput[2]','$pUInput[3]', '$pUInput[4]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
?>
Your doAction() function is buggy. You are taking the parameter into the function as $pUserInput but sending to the insert() function as $uInput.
You should do it like this:
function doAction($pUserInput)
{
// if user selects INSERT from dropdown menu, then call function insert
//and pass $uInput
if ($pUserInput[5] == "ins")
{
insert($pUserInput); // <-- FIXED: Not using correct parameter.
}
}
Change insert($uInput); function to insert($pUserInput);

Categories