mysql insert success but nothing is added - php

look at this code
<?
require_once("conn.php");
require_once("includes.php");
require_once("access.php");
if(isset($_POST[s1]))
{
//manage files
if(!empty($_FILES[images]))
{
while(list($key,$value) = each($_FILES[images][name]))
{
if(!empty($value))
{
$NewImageName = $t."_".$value;
copy($_FILES[images][tmp_name][$key], "images/".$NewImageName);
$MyImages[] = $NewImageName;
}
}
if(!empty($MyImages))
{
$ImageStr = implode("|", $MyImages);
}
}
$q1 = "insert into class_catalog set
MemberID = '$_SESSION[MemberID]',
CategoryID = '$_POST[CategoryID]',
Description = '$_POST[Description]',
images = '$ImageStr',
DatePosted = '$t',
DateExp = '$_SESSION[AccountExpDate]',
FeaturedStatus = '$_POST[sp]' ";
//echo $q1;
mysql_query($q1) or die(mysql_error());
}
//get the posted offers
$q1 = "select count(*) from class_catalog where MemberID = '$_SESSION[MemberID]' ";
$r1 = mysql_query($q1) or die(mysql_error());
$a1 = mysql_fetch_array($r1);
header("location:AddAsset.php");
exit();
?>
The mySql insert function isn't adding anything also it return success to me , I've tried using INSERT ... Values but what it done was overwtiting existing value ( i.e make 1 entry and overwties it everytime).
I am using PHP 4.4.9 and MySql 4
I tried to add from Phpmyadmin and it is working also it was working after installation but after i quit the browser and made a new account to test it it is not working but the old ones is working ! you can see it here http://bemidjiclassifieds.com/
try to login with usr:openbook pass:mohamed24 and you can see it will be working but any new account won't work!

Maybe $_POST[s1] is not set or you are inserting into a different database than you are watching.

if(isset($_POST[s1]))
should probably be
if(isset($_POST['s1']))
(note the quotes). Also, it's best to NOT depend on a field being present in the submitted data to check if you're doing a POSt. the 100% reliable method is
if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
As well, you're not checking if the file uploads succeeded. Each file should be checked like this:
foreach($_FILES['images']['name'] as $key => $name) {
if ($_FILES['images']['error'][$key] !== UPLOAD_ERR_OK) {
echo "File #$key failed to upload, error code {$_FILES['images']['error'][$key]}";
}
...
}
Don't use copy() to move uploaded files. There's a move_uploaded_files() function for that, which does some extra sanity checking to make sure nothing's tampered with the file between the time the upload finished and your script tries to move it.

Related

Cant delete files from folder using unlink function in php

Unable to delete file from folder otherwise code work perfectly.
same code i used for replacing or updating image where it works fine but here dosent able to delete data from folder by their id or name
if(isset($_POST['8maths_delete'])) //post method button name
{
$id = $_POST['delete_id']; //data fetch by id
$files_query = "DELETE FROM 8maths WHERE id='$id'"; //deleting data from sever
$files_query_run = mysqli_query($connection, $files_query); //query run
if($files_query_run) // query run
{
unlink("upload/".$row['files']); //unlink where upload folder where all the files held. but dosent able to delete file from folder
$_SESSION['success'] = "Your Data is Deleted"; //session for echo
header('Location: 8thmaths.php');
}
else
{
$_SESSION['status'] = "Your Data is not Deleted";
header('Location: 8thmaths.php'); //redirecting location
}
}
There are two issues I can see:
1 - You reference $row['files'] but I don't see $row defined anywhere in your code.
2 - Using the word 'files' I assume there could be multiple, if that's the case you need to loop over all the files and unlink them either with something like:
A foreach loop:
$result = mysqli_fetch_all($files_query_run, MYSQLI_ASSOC);
foreach($result as $row) {
unlink("upload/".$row['files']);
}
Or using a while loop.
while ($row = mysqli_fetch_assoc($files_query_run)){
unlink("upload/".$row['files']);
}
I hope this helps get you off to the right start.

foreach Data Not Updateing in database

In my local server this script works fine. When I upload this script on live it does not work properly.
It inserts only 126 rows of data into the database, but I need to upload at least 500 rows at a time.
<?php
include 'database-config.php';
foreach($_POST['classroll'] as $row=>$classroll)
{
$sclassroll = $classroll;
$mark = $_POST['mark'][$row];
$type = $_POST['rtype'];
$session = $_POST['rsession'];
$department = $_POST['rdepartment'];
$examtype = $_POST['rextype'];
$examyear = $_POST['rexyear'];
$examsubject = $_POST['rexmarksubject'];
$stmt = $dbh->prepare("INSERT INTO exammarks(studnettype, studentsession, studentdepartment, studentclassroll, examtype, examyear, examsubjec, exammarks) VALUES (:studnettype, :studentsession, :studentdepartment, :studentclassroll, :examtype, :examyear, :examsubjec, :exammarks)");
$stmt->bindParam('studnettype', $type);
$stmt->bindParam('studentsession', $session);
$stmt->bindParam('studentdepartment', $department);
$stmt->bindParam('studentclassroll', $sclassroll);
$stmt->bindParam('examtype', $examtype);
$stmt->bindParam('examyear', $examyear);
$stmt->bindParam('examsubjec', $examsubject);
$stmt->bindParam('exammarks', $mark);
$stmt->execute();
}
header('Location: ../home.php');
?>
It is possible that your exammarks table definition on your live server contains a unique index that is not present on your local host server. If that were true some of your INSERT operations might fail.
The code you showed us doesn't check for errors. Obviously, when your program deals with high value data (such as the results of student examinations) you should check for errors.
Try this instead:
if( !$stmt->execute()) {
print_r( $arr = $stmt->errorInfo() );
}
else {
/* INSERT statement completed correctly */
}

download button - save file to disk instead of opening

I have a download button and when i click on it, instead of saving to disk it opens it in the browser. I tried a bunch of attempts to make it open in the browser but it doesnt seem to do anything
<?php
// make a connection to the database
require_once("connection/connection.php");
//retrieve the ID from the url to fetch the specific details
if ($_GET['id'] != ""){
$item_id = $_GET['id'];
$bad_id = FALSE;
}
else{
$item_id = "";
$bad_id = TRUE;
}
//select the specific item from the database
// run if statement to ensure valid id was passed
if (is_numeric ($_GET['id'])){
$query = "SELECT name FROM repository WHERE item_id = '$item_id'";
$result = mysql_query($query) or die(mysql_error());
// assign the values to an array
$row = mysql_fetch_assoc($result);
//assign the values from the array to variables
$name = $row['name'];
}
// define path to the xml file
$file = "xml/".$hud_name . "_cfg.xml";
// check to make sure the file exists
if(!file_exists($file)){
die('Error: File not found.');
} else{
// Set headers
header("Content-Type: application/xml");
header("Content-Disposition:attachment; filename=".basename($file)."");
readfile($file);
}
?>
That is download.php and it obviously finds the file because it doesnt give the error about it not existing. It also echos back the correct file path
Then on another page i have:
<img src="images/download.png" alt=""/>
Any ideas whats wrong?
Well the solution turned out to be simple in the end but i didnt see any documentation saying the header must be the very first line. If i placed:
header("Content-Type: application/xml");
as the first line and then the coding below it and the other header info at the end it works. Im not sure if that's the solution or a workaround but it fixed it for me

PHP update which does not update form fields which are blank

This is an extension of a question I asked a wee while ago which #eHussain was nice enough to help out with.
I have form which inserts various details into a MySQL table and uploads a file (the name of which is also registered in the database). This works fine. The issue comes when I update, say, the name and not the image. In this case the image name is over written as 'blank', and rightly so as that's the value in the file field.
The update code:
<?php
error_reporting(E_ALL^E_NOTICE);
define('INCLUDE_CHECK',true);
include "connect.php";
$target = "../uploads/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$url=$_POST['url'];
$description=$_POST['description'];
$pic=($_FILES['photo']['name']);
$author=$_POST['author'];
$company=$_POST['company'];
$published=$_POST['published'];
$dashboardID=$_POST['dashboardID'];
//Writes the information to the database
mysql_query("UPDATE dashboard SET name='$name', url='$url', description='$description', documentName='$pic', author='$author', company='$company', publish='$published' WHERE dashboardID='$dashboardID'");
//Writes the photo to the server
if(isset($_FILES['photo']['tmp_name'])) // check if any file is uploaded
{
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
header("Location: ../dashboard.php?success=2"); } else {
header("Location: ../dashboard.php?success=0"); }
}
?>
I understand the 'isset' to avoid a the error generated if no file is selected, but I don't understand how I can extent this to avoid updating a field which has a blank value.
Do a check on the $_FILES array before running the query.
From there, you can either dynamically build the query (including or excluding the documentName field) or alternatively, fetch the current value and assign it to $pic.
For example (untested)
$values = array(
'name' => $name,
'url' => $url,
// etc
);
if (isset($_FILES['photo']['name'])) {
$values['documentName'] = $_FILES['photo']['name']
}
// mysql functions are naff, use PDO
$query = 'UPDATE dashboard SET %s WHERE dashboardID = :dashboardID';
$set = array();
foreach (array_keys($values) as $col) {
$set[] = sprintf('`%s` = :%s', $col, $col);
}
$stmt = $pdo->prepare(sprintf($query, implode(', ', $set)));
$values['dashboardID'] = $dashboardID;
$stmt->execute($values);
#rrfive , please try below method, hope it will work,
//first put all post variable in an array
$post_data = compact($_POST);
$pic=($_FILES['photo']['name']);
//now push pic name in `$post_data`
if (!empty($pic) ) { array_push( $post_data,$pic ) }
//now use UPDATE query using `vsprintf` . but first check the order of `$post_data` #Thanks Phill
$stmt = "UPDATE dashboard SET
name='%s',
url='%s',
description='%s',
author='%s',
company='%s',
publish='%s'";
$stmt .=(!empty($pic)) ? documentName='%s', : "";
$stmt .= "WHERE dashboardID=%d";
// To check the complete query before execute. uncomment below 2 lines
//print vsprintf($stmt,$post_data);
//die;
mysql_query( vsprintf($stmt,$post_data) );
Reference
- compact
- vsprintf
The following code should do the trick.
if(isset($_FILES)){
...stuff...
}

i want help to build my logic?

hey i guys i want help from you.
i am working on website project, in that i want to create "if user upload some data then it will be stored in his folder" for this i want currently login username.Because the folder name=username.
when user register to my website it will create folder in webspace which name=username.
now i want to take currently login username for defining path to uploaded image.
i give you example:
if (isset($_SESSION['username']))
{
$username=($_SESSION['username']);
$CHECK=mysql_query("Select `status` from `user_reg` where `username`=$username");
if ($check="Admin") {
$userimage="/Place4Info/Data/Admin_data/".$username."/";
} else {
$userimage="/Place4Info/Data/User_data/".$username."/";
}
i save path in $userimage & then use it everywhere.
above code is not running
Use double =:
if ($check == "Admin") {
$userimage="/Place4Info/Data/Admin_data/".$username."/";
First, $CHECK is not the same as $check. Second, $CHECK is a mysql resource, not a string containing a value from the database. Third, you can print mysql_error() after mysql_query() to determine wheter the query failed and why.
Something like:
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$res = mysql_query("Select status from user_reg where username='$username'");
$row = mysql_fetch_assoc($res);
$check = $row['status'];
if ($check == "Admin") {
$userimage = "/Place4Info/Data/Admin_data/".$username."/";
}
else {
$userimage = "/Place4Info/Data/User_data/".$username."/";
}
}
you need to use mysql_fetch_array on the result of your query:
$res = mysql_query("Selectstatusfromuser_regwhereusername=$username");
$check = mysql_fetch_array($res);
Also I noticed you are switching between UPPERCASE check and lowercase, you can't mix them up in PHP.

Categories