Image edit and mysql - php

I have a simple table for reference page:
id name description image
In reference.php, A form upload image to a folder and save image's name in image section.
In reference.php?action=edit page I want to edit the image. What is correct way to edit? Uploading another image and update the table?
Functions:
function editRef() {
?>
<?php
$row = queryWithID('reference');
EpUpload();
?>
<div class="form">
<form action="" method="post" enctype="multipart/form-data">
<ul>
<li><label>Name</label></li>
<li><input name="refname" type="text" class="inp" value="<?php echo $row['name']; ?>" /></li>
<li><label>Description</label></li>
<li><textarea name="reftext" cols="" rows=""><?php echo $row['description']; ?></textarea></li>
<li><label>Image</label></li>
<li><input name="refile" type="file" /></li>
<li><label>Sıra</label></li>
<li><input name="reforder" type="text" class="inp"/></li>
<li><input name="refsubmit" type="submit" value="Edit" class="int"/></li>
</ul>
</form>
</div>
<?php
}
function EpUpload() {
$refsubmit = safe_mysql('refsubmit');
$reftext = safe_mysql('reftext');
$refname = safe_mysql('refname');
$reforder = safe_mysql('reforder');
$refile = $_FILES['refile']['name'];
$tmp = $_FILES['refile']['tmp_name'];
$fileType = $_FILES['refile']['type'];
$path = SITE_ROOT."uploads/images/";
if($refsubmit){
$require_fields = array("$reftext","$refname", "$reforder");
if(checkBlank($require_fields)){
echo "<p class='not'><span>Please fill all inputs!</span></p>";
}
else{
move_uploaded_file($tmp, $path.$refile);
$query = "UPDATE reference SET name = '$refname', order='$reforder' description = '$reftext', image = '$refile' WHERE id = $id ";
$result = mysql_query($sql);
if(mysql_affected_rows () == 1){
echo "<p class='ok'><span>rBlah blah</span></p>";
}
else{
echo mysql_error();
}
}
}
}
function queryWithID($table){
if(is_numeric($_GET['id'])){ $id = mysql_real_escape_string($_GET['id']);}
$sql = "SELECT * FROM $table WHERE id= $id";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
return $row ;
}
Thanks

yes, this way is correct.
Well, how I do it:
note this code:
if ($_FILES['userfile']['name'] AND !$_FILES['userfile']['error']) {
move_uploaded_file($_FILES['userfile']['tmp_name'],$cfg['upload_path'].$id.".jpg");
}
it will move the file only if there was a file and no error.
Note 3 parts of this script.
Ahhh almost forgot it!
I do not save the original file name but use id for it.
<?
include 'cfg.php';
$table=$cfg['db_table'];
$data=array();
$pic='';
$fields=array('title','section','price','annot','visible');
if($_SERVER['REQUEST_METHOD']=='POST') {
if ($id=intval($_POST['id'])) {
$query="UPDATE $table SET ".dbSet($fields)." WHERE id=$id";
} else {
$query="INSERT INTO $table SET ".dbSet($fields);
}
mysql_query($query) or die(mysql_error());
if (!$id) {
$id=mysql_insert_id();
}
if ($_FILES['userfile']['name'] AND !$_FILES['userfile']['error']) {
move_uploaded_file($_FILES['userfile']['tmp_name'],$cfg['upload_path'].$id.".jpg");
}
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
include $cfg['tpl_header'];
if (!isset($_GET['id'])) {
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
?>
<br>Add item<br><br>
<? foreach ($LIST as $row): ?>
<li><?=$row['title']?>...
<? endforeach ?>
<?
} else {
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
if ($row['visible']) $row['visible']=" checked";
if (is_readable($cfg['upload_path'].$id.".jpg")) $pic=$id.".jpg";
} else {
foreach ($fields as $k => $v) $row[$v]='';
}
?>
<form method="POST" enctype="multipart/form-data">
<table border=0>
<tr><td>Name</td><td><input type="text" name="title" size="100" value="<?=$row['title']?>"></tr>
<tr><td>Price</td><td><input type="text" name="price" size="100" value="<?=$row['price']?>"></tr>
<tr><td>Descr</td><td><textarea rows="20" cols="80" name="annot"><?=$row['annot']?></textarea></tr>
<tr><td>Visible</td><td><input type="checkbox" name="visible" value="1" checked></tr>
</table>
<?if(isset($row['id'])):?> <input type="hidden" name="id" value="<?=$row['id']?>"><?endif?>
Picture:<input name="userfile" type="file" /><br>
<input type="submit">
<br><br>
Back to list
</form>
<? if($pic): ?>
<img src="img/<?=$pic?>">
<? endif ?>
<?
}
include $cfg['tpl_footer'];
?>

Related

PHP - Undefined index : id - the value is not retrieved

Yes, I know there is a lot of 'Undefined index' questions floating around here and i have been looking through them before asking this question. I copied the codes from those questions to try and test it out but it still doesn't work for my own project. Also, I'm still a beginner in PHP.
So here is my problem. I wanted to try coding a simple edit form after I have finished coding the delete and view form.
This is my code
<?php
require("config.php");
$id = $_GET['id'];
echo "id: ".$id;
$sql = "SELECT * FROM contracts WHERE id= '$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc()
?>
<form action="editform.php" method="GET">
ID:
<?php echo $id; ?><br>
Contract Title<br>
<input type="text" name="contract_title" value="<?php echo $row['contract_title']; ?>" /><br>
<input type="submit" name = "edit "value="Update" />
</form>
?php
if(isset($_POST['edit']) ){
$id = $_GET['id'];
$upd= "UPDATE `contracts` SET
`contract_title`='".$_POST['contract_title']."',
WHERE `id`='".$_POST['id']."";
if($do_upd = $con->query($upd))
{
echo "Update Success";
}
else
{
echo "Update Fail";
}
}
?>
This is the before the error.
This is the error I received.
In line 3, the id is not retrieved after I clicked the button update.
It didn't retrieved the values.
What mistakes did I do in the coding and how do I fix it? Thanks in advance.
Right below:
<form action="editform.php" method="GET">
Add:
<input type="hidden" name="id" value="<?php echo $id; ?>" />
Update:
Fixed other errors in your code:
<?php
require("config.php");
$id = $_GET['id'];
echo "id: ".$id;
$sql = "SELECT * FROM contracts WHERE id= '$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc()
?>
<form action="editform.php" method="GET">
ID: <?php echo $id; ?><br>
Contract Title<br>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="contract_title" value="<?php echo $row['contract_title']; ?>" /><br>
<input type="submit" name="edit" value="Update" />
</form>
<?php
if(isset($_GET['edit']) ){
// needs escaping!~~~
$upd= "UPDATE `contracts` SET `contract_title` = '".$_GET['contract_title']."' WHERE `id` = '".$id;
if($do_upd = $con->query($upd)) {
echo "Update Success";
} else {
echo "Update Fail";
}
}
Please consider escaping your database input to prevent SQL injection
<?php
require("config.php");
$id = $_GET['id'];
echo "id: ".$id;
$sql = "SELECT * FROM contracts WHERE id= '$id'";
$result = $con->query($sql);
$row = $result->fetch_assoc()
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$contract_title = $row['contract_title'];
}
} else {
echo "0 results";
}
if(isset($_POST['edit']) ){
$upd = "UPDATE contracts SET contract_title='$contract_title' WHERE id='$id'";
if($do_upd = $con->query($upd))
{
echo "Update Success";
}
else
{
echo "Update Fail";
}
}
?>
<form action="" method="POST">
ID:
<?php echo $id; ?><br>
Contract Title<br>
<input type="text" name="contract_title" value="<?php echo $row['contract_title']; ?>" /><br>
<input type="submit" name = "edit" value="Update" />
</form>

PHP - Update all Fields at the same time AND delete image for each field independently

I am currently creating a basic CMS for practice purposes and I can't seem to figure out:
How to Update all fields at once AND delete (or upload new) images for each independent record
Any help would be appreciated :)
Updating All Fields Code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$sql = "UPDATE services SET page_title=:pageTitle, event_title=:eventTitle, event_content=:eventContent WHERE id=:id";
foreach ($id as $key => $value) {
$query = $connect->prepare($sql);
$query->bindValue(':pageTitle', $_POST['page_title'], PDO::PARAM_STR);
$query->bindValue(':eventTitle', $_POST['event_title'][$key], PDO::PARAM_STR);
$query->bindValue(':eventContent', $_POST['event_content'][$key], PDO::PARAM_STR);
$query->bindValue(':id', $id[$key], PDO::PARAM_STR);
if ($query->execute()) {
$message = 'Records updated.';
} else {
$message = "Failed to update records. Please contact Administrator.";
}
}
}
PHP/HTML Code:
<form method="post" action="">
<?php
$sql = "SELECT * FROM services";
$query = $connect->prepare($sql);
$query->execute();
$i = 1;
while($results = $query->fetch(PDO::FETCH_ASSOC)) { ?>
<?php if ($i === 1) { ?>
<input type="text" value="<?php echo $results['page_title'] ?>" name="page_title">
<?php } ?>
<div class="service">
<input type="hidden" value="<?php echo $results['id'] ?>" name="id[]">
<input type="text" value="<?php echo $results['event_title'] ?>" name="event_title[]"/>
<?php
if ($results['event_imgSrc'] == '') { ?>
<img src='' style="width:100px; height:100px;">
<?php } else { ?>
<img src="<?php echo '../'.$results['event_imgSrc'] ?>" name="event_imgSrc">
<?php }
?>
<input type="file" name="image">
<input type="submit" name="del_img" value="Delete Image">
<input type="submit" name="upload_new" value="Upload New Image">
<textarea name="event_content[]"><?php echo $results['event_content'] ?></textarea>
</div>
<?php $i++; } ?>
<input type="submit" name="submit" value="Update"/>
<?php if (isset($message)) { ?>
<p><?php echo $message ?></p>
<?php } ?>
</form>

Add-to-cart coding is that correct with form?

<?php
session_start();
include("conn.php");
$action = $_POST['action'];
$user = $_SESSION['username'];
if(empty($user)){
echo"<script>alert('Please log in!');window.location='Log In.php';</script>";
exit;
}
if($action == 'add'){
$cart_arr = array(
'foodID'=>$_POST['foodID'],
'order_num'=>$_POST['order_num'],
'food_type'=>$_POST['food_type'],
);
$cart_session = $_SESSION['cart_'.$user];
if(empty($cart_session)){
$cart_session[$cart_arr['foodID']] = $cart_arr;
} else if(!empty($cart_session[$cart_arr['foodID']])){
$cart_session[$cart_arr['foodID']]['order_num']+=$cart_arr['order_num'];
} else {
echo $cart_session[$cart_arr['foodID']] = $cart_arr;
}
$_SESSION['cart_'.$user] = $cart_session;
} else if($action == 'clear'){
$_SESSION['cart_'.$user]=array();
echo"<script>alert('Shopping cart is empty, return home!');window.location='homepage.php';</script>";
exit;
} else if($action == 'change'){
$temp_cart = $_SESSION['cart_'.$user];
foreach($temp_cart as $k=>$v){
if($_POST['goods_'.$k]!= $v['order_num']){
$temp_cart[$k]['order_num'] = $_POST['goods_'.$k];
}
if($_POST['goods_'.$k] == 0){
unset($temp_cart[$k]);
}
}
$_SESSION['cart_'.$user] = $temp_cart;
}
if(empty($_SESSION['cart_'.$user])){
echo"<script>alert('Shopping cart is empty, please add some orders!');window.location = 'homepage.php';</script>";
exit;
}
$goods_id = array();
$cart = $_SESSION['cart_'.$user];
$v['food_type'] = $_POST['food_type'];
foreach($cart as $k=>$v){
$goods_id[$v['foodID']] = $v['foodID'];
}
$goods_id_str = implode(",",$goods_id);
mysql_query("set names utf8");
$sql = "select * from foodmenu where foodID IN (".$goods_id_str.")";
$query = mysql_query($sql);
$cart_goods = array();
while($arr = mysql_fetch_array($query)){
$cart_goods[$arr['foodID']] = $arr;
}
foreach($cart as $k=>$v){
$cart[$k]['food_name'] = $cart_goods[$k]['food_name'];
$cart[$k]['food_img'] = str_replace("../","",$cart_goods[$k]['food_img']);
$cart[$k]['food_price'] = $cart_goods[$k]['food_price'];
$cart[$k]['food_description'] = $_POST['food_description'];
}
?>
May I know is that this coding correct?
Because it shows blank page when it click on the button on previous php for add-to-cart purpose and it just shows normal header at the top.
I will attach form to access this php.
<div class="detailtop">
<?php
$result = mysql_query("SELECT * FROM foodmenu where foodID = '$foodID'");
while($row=mysql_fetch_array($result)){
?>
<dl>
<dt>
<img src="<?php echo $row["food_img"];?>" /> </dt>
<dd>
<form action="order.php" method="get" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<h3><?php echo $row["food_name"];?></h3>
<div class="detailtips">
<?php echo $row["food_description"];?>
</div>
<p><span>Restaurant:</span><strong><?php echo $row["restaurant_name"];?></strong></p>
<p><span>Type :</span><strong><?php echo $row["food_type"];?></strong></p>
<p><span>Price :</span>RM <strong><?php echo $row["food_price"];?><input name="num" type="hidden" class="num" value="<?php echo $row["food_price"];?>" /></strong></p>
<div class="order" style=" padding-top:20px; padding-left:20px;">
<input name="id" type="hidden" value="<?php echo $row["foodID"];?>" />
<input name="" type="submit" value="" class="ordersubmit" style=" margin-left:30px; margin-top:20px;">
</div>
</form>
</dd>
</dl>
<?php }?>
</div>

Display saved checkbox value

I have some checkbox options that I save in the DB. I was able to view and also select multiple options and save them in the DB. The issue is that I want to display the saved information but I don't know how to do that.
<form action="save_comp.php" method="post">
<?php
//Display
include ('mysql_connect.php');
$sql = mysql_query("SELECT * FROM competency ");
//$row = mysql_fetch_array($sql);
while($row = mysql_fetch_array($sql))
{
echo"<input type='checkbox' name='comp[]' value= ".$row['id']." /> ".$row['competency']." <br />";
}
?>
<input name="submit" type="submit" value="submit" />
</form>
Save into DB
<?php
session_start();
$id = $_SESSION['user_id'];
//$id = 3;
include ('mysql_connect.php');
$insStr = '';
foreach($_POST['comp'] as $val){ $insStr .=$val.","; }
mysql_query("INSERT INTO competency_result (user_id,result) VALUES ( '$id', '$insStr' )") or die(mysql_error());
echo'<script>alert("Inserted Successfully")</script>';
?>
All I want to do now is to display the saved information in a table format. I tried doing this but it only showed me the saved ID
<?php
$res= mysql_query("SELECT * FROM competency_result WHERE user_id = '$user'")or die(mysql_error());
while($row = mysql_fetch_array($res))
{
echo"<tr>";
echo"<td> $row[result]</td>";
?>
<?php
echo"</tr>";
}
?>
<form action="save_comp.php" method="post">
<?php
//Display
include ('mysql_connect.php');
$sql = mysql_query("SELECT * FROM competency ");
//$row = mysql_fetch_array($sql);
while($row = mysql_fetch_array($sql))
{
echo"<input type='checkbox' name='comp[". $row['id']. "]' value='". $row['competency'] ."' /> ".$row['competency']." <br />";
}
?>
<input name="submit" type="submit" value="submit" />
</form>
If you want to checkboxes check then you can try with below code:
<?php
$sql = mysql_query("SELECT name FROM competency ");
//$row = mysql_fetch_array($sql);
while($row = mysql_fetch_array($sql))
{
$focus=explode(",",$row['name']);
?>
<input type="checkbox" name="focus[]" value="Art" <?php if(in_array("Comp",$focus)) { ?> checked="checked" <?php } ?> >
<input type="checkbox" name="focus[]" value="Mathematics" <?php if(in_array("Mathematics",$focus)) { ?> checked="checked" <?php } ?> >
<input type="checkbox" name="focus[]" value="Dance" <?php if(in_array("Dance",$focus)) { ?> checked="checked" <?php } ?> >
<?php
}
?>

edit_subject.php is not working, the error is saying about database query failed

This is kind of the error I'm getting:
Database query failed.
I've uploaded this webpage: http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1
Here's my file:
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/db_connection.php"); ?>
<?php require_once("../includes/functions.php"); ?>
<?php require_once("../includes/validation_functions.php"); ?>
<?php find_selected_page(); ?>
<?php
if (!$current_subject)
{
// subject ID was missing or invalid or
// subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit']))
{
// validations
$required_fields = array("menu_name", "position", "visible");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 30);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors))
{
// Perform Update
$id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "UPDATE subjects SET ";
$query .= "menu_name='{$menu_name}', ";
$query .= "position={$position}, ";
$query .= "visible={$visible} ";
$query .= "WHERE id={$id} ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) >= 0)
{
// Success
$_SESSION["message"] = "Subject updated.";
redirect_to("manage_content.php");
}
else
{
// Failure
$message = "Subject update failed.";
}
}
}
// else
// {
// // This is probably a GET request
// }
?>
<?php include("../includes/layouts/header.php"); ?>
<div id="main">
<div id="navigation">
<?php
echo navigation($current_subject, $current_page);
?>
</div>
<div id="page">
<?php
// echo message();
// $message is just a variable, doesn't use the SESSION
if(!empty($message))
{
echo "<div class=\"message\">" . htmlentities($message) . "</div>";
}
?>
<?php echo form_errors($errors); ?>
<h2>Edit Subject: <?php echo htmlentities($current_subject["menu_name"]); ?></h2>
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="<?php echo htmlentities($current_subject["menu_name"]); ?>" />
</p>
<p>Position:
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
for ($count=1; $count <= $subject_count; $count++)
{
echo "<option value=\"{$count}\"";
if ($current_subject["position"] == $count)
{
echo " selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" <?php if ($current_subject["visible"] == 0) { echo "checked"; } ?> /> No
<input type="radio" name="visible" value="1" <?php if ($current_subject["visible"] == 1) { echo "checked"; } ?> /> Yes
</p>
<input type="submit" name="submit" value="Edit Subject" />
</form>
<br />
Cancel
Delete Subject
</div>
The problem is somewhere else and not with your UPDATE query actually. If you see the link you posted, you are passing subject parameter with url, whose value is 1 which is integer.
Now when you click submit it's changing the url to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=About%20Widget%20Corp .
Here as you see the subject parameter is not integer but string value name of subject. And that is causing the problem.
You are getting error as it's not retrieving the subject data from database correctly because of wrong id type. You just need to make sure the form is being posted to right url, which would be http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1.
You need to correct the action parameter on the <form> tag for that.
Look for the line below in your code:
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["menu_name"]); ?>" method="post">
And change it to
<form action="edit_subject.php?subject=<?php echo htmlentities($current_subject["id"]); ?>" method="post">
If you see, now the form will be submitted to http://widgetcorp.bugs3.com/public/edit_subject.php?subject=1, which is the correct url.

Categories