I am not very much familiar with the OOPs in PHP. Just getting some simple lessons from the net i have tried to make a class to dynamically insert,delete update , upload data from the form to the database tables...
I am not sure if it is really object oriented.. Anybody could help me locate the errors or just make it better....
To use this class...Here are some rules or necessity:
1. The fields in the form should have same name as that of the fields in database..
2. The name of 'Submit' button should be same as that of the TABLE the form is going to insert data into.
3. No field in form(table) should have a same name as that of ANY TABLE in database.(except submit button)
To insert use function INSERTDB..
and
If there is an image upload use IMAG...
Here's the code:
db.class.php
<?php class database{
var $user,$host,$pass,$db;
public function connect($user,$host,$pass,$db){
$this->user=$user;
$this->host=$host;
$this->pass=$pass;
$this->db=$db;
$this->mysqli=new mysqli($this->user,$this->host,$this->pass,$this->db);
if ($this->mysqli->connect_error) {
die('Error : ('. $this->mysqli->connect_errno .') '. $this->mysqli->connect_error);
}
}
function imag($path,$tb){
define ("MAX_SIZE","400");
$errors=0;
$imag =$_FILES["image"]["name"];
$j=date("Y.m.d");
$image=$j.$imag;
$uploadedfile = $_FILES['image']['tmp_name'];
if ($image)
{
$filename = stripslashes($_FILES['image']['name']);
$extension =substr($image,-3);
echo "<br>".$extension."<br>".$image;
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg")
&& ($extension != "png") && ($extension != "gif"))
{
echo ' Unknown Image extension ';
$errors=1;
}
else
{
$size=filesize($_FILES['image']['tmp_name']);
if ($size > MAX_SIZE*1024)
{
echo "You have exceeded the size limit";
$errors=1;
}
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['image']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['image']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else
{
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newwidth=800;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$newwidth1=150;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
$width,$height);
imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,
$width,$height);
$filename = "../images/".$path."/". $image;
$filename1 = "../images/".$path."/s/". $image;
imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);
imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
//If no errors registred, print the success message
if(!$errors)
{
// mysql_query("update SQL statement ");
$this->insertdb($tb);
echo "Image Uploaded Successfully!";
}
}
function insert($tb,$field,$value){
$in= mysqli_query($this->mysqli,"INSERT INTO $tb ($field) values ($value)");
if(!$in){
die("Insert Query Failed" .mysqli_error($this->mysqli) );
}
}
function insertdb($tb){
echo $tb;
$f="";
$v="";
foreach($_POST as $key=>$value){
echo $key . " = " . $value. "<br>";
}
foreach($_POST as $key=>$value){
if(($key!==$tb)&&($key!=="image_y")){
$f=$f.mysqli_real_escape_string($this->mysqli,$key).",";
$v=$v."'".mysqli_real_escape_string($this->mysqli,$value)."',";
echo "<hr> there is no image<hr>";
}
if($key=="image_y"){
$f=$f."image,";
$v=$v."'".$_FILES['image']['name']."',";
echo "<hr> there is an image<hr>";
}
}
$f1=rtrim($f,",");
$v1=rtrim($v,",");
echo $f1 ."<br>".$v1;
$this->insert($tb,$f1,$v1);
}
function del($tb,$field,$value){
$d= mysqli_query($this->mysqli,"DELETE FROM $tb where $field = '$value' ");
if(!$d){
die("Delete Query Failed" );
}
}
function up($tb,$field,$value,$o_field,$o_value){
$u= mysqli_query($this->mysqli,"UPDATE $tb SET $field= '$value' where $o_field= '$o_value' ");
if(!$u){
die("Update Query Failed".mysqli_error($this->mysqli) );
}
}
function show($tb,$field,$value,$condition,$ans){
$s= mysqli_query($this->mysqli,"Select * from $tb where $field $condition '$value' ");
$s2=mysqli_fetch_assoc($s);
echo $s2[$ans];
if(!$s){
die("Select Query Failed".mysqli_error($this->mysqli) );
}
}
}
?>
process.php
<?php
include"../includes/db.class.php";
$o=new database();
$o->connect("localhost","root","","saycheese");
if(isset($_POST['category'])){
$tb="category";
$o->insertdb($tb);
}
if(isset($_POST['magzine'])){
$tb="magzine";
$o->insertdb($tb);
}
if(isset($_POST['writer'])){
$tb="writer";
$folder="wr";
$o->imag($folder,$tb);
}
if(isset($_POST['images'])){
$tb="images";
$folder="mag";
$o->imag($folder,$tb);
}
?>
`
Foreword
You're on the right track, but you're only half way there. you have to format your data before you can insert anything to the database.
This means, you must map your $_POST values to the the arrays $field and $value, the former being the database columns and the latter being the data you wish to insert.
The insert() method takes 3 inputs. $tb $field and $value
$tb is easy its a string. $field and $value are most likely arrays, depending on your table structure. even if your table contains a single column, it would still be best to use arrays. there are two syntax for working with arrays. the first being [] (only supported on newer php installations), and the older but more supported 'array()' method.
Addressing the problem
In your code, you are incorrectly using the insertdb method which is only for tables that have the same column name as post fields. otherwise, this method will not work. instead, you should focus on using the insert() method, and correctly mapping the values.
say you have a table structure like so
TABLE user_info
user_name (VARCHAR(25)
pass_word VARCHAR(255)
user_id PRIMARY, AI INT(11)
As you can see, for a successful insert, you must provide values for user_name and pass_word while user_id is your primary index and will autoincrement.
Now, say you have a post like so
$username = $_POST['user'];
$password = $_POST['pass'];
Knowing this, we have to somehow map this information to our database.
PRESTO! We can map them like so
$tb = 'user_info';
$field = ['user_name','pass_word'];
$value = [$username,$password];
now, we have all the prerequisites for inserting with our db class.
$o->insert($tb,$field,$value);
It's very messy at the moment. You need to abstract more to really make this OO. I would stick the connection stuff in another file and then turn this into a callable object.
What do I mean by this? Well, you can return the whole file as an object by returning $this in every function. For example, let's look at a where function.
//Db would hold your connection details and connect to the DB
class Query_Builder extends Db {
//Declare your instance variables here, we are just doing where for the purposes of this
protected $_where;
public function where($column, $field)
{
//Encaps in single quotes
$encapsField = '\'' . $field . '\'';
$newWhere = str_replace('?', $encapsField, $column);
$this->_where = 'WHERE ' . $newWhere;
return $this;
}
Note: You don't need public on the function, as it is declared implicitly anyway, but it is considered good practice to always declare functions explicitly.
This function will return $this->_where set to something like 'WHERE id = '1';'. Using this, you can build whole queries by repeating this process. This is a lot more object orientated and will give you good grounding to expand your class to incorporate these design patterns.
Related
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);
}
}
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
I'm not sure why but in my image upload script none of my data is being entered into the database. This is the same script I've been using, but I recently added to if(isset)) statements to see if certain checkboxs were checked. The images are being uploaded to the server, but the database table remains empty. Any clues? I'm not getting any errors.
if(isset($_POST['submit'])) {
$count = count($_FILES['img_file']['name']);
for($i = 0; $i < $count; ++$i){
$img_name = $_POST['img_name'];
$img_name = str_replace(' ', '_', $img_name);
$img_album = $_POST['img_album'];
$img_album = str_replace(' ', '_', $img_album);
$img_photographer = $_POST['img_photographer'];
$img_location = $_POST['img_location'];
if(isset($_POST['horror'])) { $horror = "1"; } else { $horror = "0"; }
if(isset($_POST['occult'])) { $occult = "1"; } else { $occult = "0"; }
if(isset($_POST['goth'])) { $goth = "1"; } else { $goth = "0"; }
if(isset($_POST['industrial'])) { $industrial = "1"; } else { $industrial = "0"; }
if(isset($_POST['fashion'])) { $fashion = "1"; } else { $fashion = "0"; }
if(isset($_POST['fetish'])) { $fetish = "1"; } else { $fetish = "0"; }
if(isset($_POST['avante-garde'])) { $avanteGarde = "1"; } else { $avanteGarde = "0"; }
if(isset($_POST['cosplay'])) { $cosplay = "1"; } else { $cosplay = "0"; }
if(isset($_POST['nude'])) { $nude = "1"; } else { $nude = "0"; }
$file_name = $_FILES["img_file"]["name"][$i];
$file_ext = end((explode(".", $file_name)));
$target = $_SERVER['DOCUMENT_ROOT']."/gallery/";
$img_rename = $img_name . '_' . $i . '.' . $file_ext;
$target = $target . $img_rename;
if(move_uploaded_file($_FILES['img_file']['tmp_name'][$i], $target)){
mysqli_query($conn, "INSERT INTO gallery_img (img_name, img_album, img_photographer, img_location, horror, occult, goth, industrial, fashion, fetish, avante-garde, cosplay, nude, file_location) VALUES ('$img_name', '$img_album', '$img_photographer', '$img_location', '$horror', '$occult', '$goth', '$industrial', '$fashion', '$fetish', '$avanteGarde', '$cosplay', '$nude', '$img_rename')") ;
echo '<div class="alert alert-success margin-top">Image "'.$file_name.'" successfully uploaded and renamed to '.$img_rename.'.</div>';
}else {
echo '<div class="alert alert-danger margin-top">Sorry, there was a problem uploading your images.</div>';
}
}
}
You obviously weren't checking for errors in your query.
Notice the hyphen for one of your columns? It seems that others may have not scrolled over to the right (enough) to see it and to inform you about it.
avante-garde
MySQL is interpreting that as:
avante minus garde and thinking you wanted to do math. It should either be renamed using an underscore as you did for some of your other columns, or wrap it with ticks.
I.e.:
`avante-garde`
Btw, (and I'm not criticizing); that word is actually spelled "avant-garde", so make sure it is in fact that actual name. In either case, it would have failed you.
Note: I'm really hoping that that wasn't a typo on your part and that you are/were using an underscore after all.
Using error checking on the query in a conditional statement would have helped.
I.e. and assign a variable to it:
$query = mysqli_query($conn, "INSERT INTO gallery_img (...) VALUES (...)");
then
if($query){
echo "Success";
} else {
echo "Error: " . mysqli_error($conn);
}
http://php.net/manual/en/mysqli.error.php
Another thing. Make sure the column types are correct and of the right length. MySQL can fail silently if the lengths aren't long enough to accommodate the data.
Do use a prepared statement; your code is presently open to an SQL injection.
https://en.wikipedia.org/wiki/Prepared_statement
Footnotes:
You may want to look into using a ternary operator instead of some/all those if{...} else{...} statements, plus it's a lot shorter code.
http://php.net/manual/en/language.operators.comparison.php
Example from the manual:
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
Of course, you can replace empty with isset.
There is something worth noting and that could (also) prevent your query from executing, and that is its location for the query.
You have it inside the following condition. If your upload fails, so will the query.
if(move_uploaded_file($_FILES['img_file']['tmp_name'][$i], $target)){
mysqli_query($conn, "INSERT INTO gallery_img (...) VALUES (...)");
echo '<div class="...">Success...</div>';
}else {
echo '<div class="...">Error...</div>';
}
A few possible reasons why the upload failed, and could be one of any of the following:
File(s) is(are) too large
Permissions are not set for the folder to write to.
Typo(s) for the file(s) inputs(s)
Other
Reference for upload error codes/messages:
http://php.net/manual/en/features.file-upload.errors.php
end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}
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