count messages that sent by users in my chat - php

first i have a chat script and every user in my chat have his own profile and some information inside his profile like, country, age, grinder, his photo and his friends, somehow i need to display the count of his all messages that he had sent in chat, and i'll make a new field in his profile ti put this number.
so here i have this function that store messages for users in database.
function userPostChat($content, $snum = ''){
global $mysqli, $data;
$lact = calMinutes(3);
$style = escape($data['bccolor'] . ' ' . $data['bcbold']);
$mysqli->query("INSERT INTO `my_chat` (post_date, user_id, post_message, post_roomid, type, snum, tcolor) VALUES ('" . time() . "', '{$data['user_id']}', '$content', '{$data['user_roomid']}', 'public', '$snum', '$style')");
$last_id = $mysqli->insert_id;
$mysqli->query("UPDATE my_users SET caction = caction + 1 WHERE user_roomid = '{$data['user_roomid']}' and last_action > '$lact'");
if($snum != ''){
$user_post = array(
'post_id'=> $last_id,
'type'=> 'public',
'post_date'=> time(),
'tcolor'=> $style,
'post_message'=> $content,
);
$post = array_merge($data, $user_post);
if(!empty($post)){
return createLog($data, $post);
}
}
}
i forget to say that function already count messages from all users and store it in column inside my_users table called ' caction ' but this function count the messages for all users in the same time like, if i have 0 points and someone sent a message in chat it will count this message for me and him and all users in chat, and i don't wanna it, i want a function to count messages for every user and display the number.
here is my tables:
Table my_users
user_id
user_name
password
user_photo
user_email
room_id
caction
Table my_chat
post_id
user_id
post_date
post_message
post_roomid
type
snum
tcolor
and here i have my chat_file.php
function userPostChatFile($content, $file_name, $type, $file_name2 = ''){
global $mysqli, $data;
$lact = calMinutes(3);
$mysqli->query("INSERT INTO `my_chat` (post_date, user_id, post_message, post_roomid, type, file) VALUES ('" . time() . "', '{$data['user_id']}', '$content', '{$data['user_roomid']}', 'public', '1')");
$rel = $mysqli->insert_id;
$mysqli->query("UPDATE my_users SET caction = caction + 1 WHERE user_roomid = '{$data['user_roomid']}' and last_action > '$lact'");
if($file_name2 != ''){
$mysqli->query("INSERT INTO `my_upload` (file_name, date_sent, file_user, file_zone, file_type, relative_post) VALUES
('$file_name', '" . time() . "', '{$data['user_id']}', 'chat', '$type', '$rel'),
('$file_name2', '" . time() . "', '{$data['user_id']}', 'chat', '$type', '$rel')
");
}
else {
$mysqli->query("INSERT INTO `my_upload` (file_name, date_sent, file_user, file_zone, file_type, relative_post) VALUES ('$file_name', '" . time() . "', '{$data['user_id']}', 'chat', '$type', '$rel')");
}
return true;
}
if(!myAllow($data['allow_image']) || muted() || roomMuted()){
die();
}
if (isset($_FILES["file"])){
ini_set('memory_limit','128M');
$info = pathinfo($_FILES["file"]["name"]);
$extension = $info['extension'];
$origin = escape(filterOrigin($info['filename']) . '.' . $extension);
if ( fileError() ){
echo 1;
die();
}
if (isImage($extension)){
$imginfo = getimagesize($_FILES["file"]["tmp_name"]);
if ($imginfo !== false) {
$width = $imginfo[0];
$height = $imginfo[1];
$type = $imginfo['mime'];
$fname = encodeFileTumb($extension);
$file_name = $fname['full'];
$file_tumb = $fname['tumb'];
move_uploaded_file(preg_replace('/\s+/', '', $_FILES["file"]["tmp_name"]), "../upload/chat/" . $file_name);
$source = '../upload/chat/' . $file_name;
$tumb = '../upload/chat/' . $file_tumb;
$img_path = $data['domain'] . "/upload/chat/" . $file_name;
$tumb_path = $data['domain'] . "/upload/chat/" . $file_tumb;
$create = imageTumb($source, $tumb, $type, 180);
if(file_exists($source) && file_exists($tumb)){
$check_tumb = getimagesize($tumb);
if ($check_tumb !== false) {
$myimage = tumbLinking($img_path, $tumb_path);
userPostChatFile($myimage, $file_name, 'image', $file_tumb);
}
else {
$myimage = linking($img_path);
userPostChatFile($myimage, $file_name, 'image');
}
}
else {
$myimage = linking($img_path);
userPostChatFile($myimage, $file_name, 'image');
}
echo 5;
die();
}
else {
echo 1;
die();
}
}
else if (isFile($extension)){
$file_name = encodeFile($extension);
move_uploaded_file(preg_replace('/\s+/', '', $_FILES["file"]["tmp_name"]), "../upload/chat/" . $file_name);
$myfile = $data['domain'] . "/upload/chat/" . $file_name;
$myfile = fileProcess($myfile, $origin);
userPostChatFile($myfile, $file_name, 'file');
echo 5;
die();
}
else if (isMusic($extension)){
$file_name = encodeFile($extension);
move_uploaded_file(preg_replace('/\s+/', '', $_FILES["file"]["tmp_name"]), "../upload/chat/" . $file_name);
$myfile = $data['domain'] . "/upload/chat/" . $file_name;
$myfile = musicProcess($myfile, $origin);
userPostChatFile($myfile, $file_name, 'music');
echo 5;
die();
}
else {
echo 1;
}
}
else {
echo 1;
}
?>
so how i can make a function to count messages for each user and store it in column in my_users table.

Run this query you will get the number of messages send by each user. You can either display the count on his page or store it somewhere and display it.
SELECT COUNT(*) AS no_messages FROM my_chat WHERE user_id = <user id here>

Related

Import csv from file with dynamic table head

I'm having a problem with my importing csv script into mysql:
from now i can put the data from csv into mysql but only with strictly header arrange, but my export from csv always change the head of table, and i cannot control it.
my csv file is different from the table for example:
Name Status Last_name email_address employee_address phone_number
And all i need is to take the column name and put it into right column from table.
Thanks.
if (isset($_POST["import"])) {
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0) {
$file = fopen($fileName, "r");
$captabel = true;
$flag = true;
while (($column = fgetcsv($file, 1000, ",")) !== FALSE) {
if($captabel) { $captabel = false; continue; }
$celuleNecesare = array(0);
foreach ($celuleNecesare as $value) {
if(trim($column[$value]) == "" || $column[$value] == NULL)
$flag = false;
}
if($flag) {
$query = "INSERT into test (name ,employee_status, surname, email, address, phone)
values ('" . $column[2] . "','" . $column[7] . "','" . $column[8] . "','" . $column[5] . "','" . $column[0] . "','0" . $column[3] . "')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
header( 'refresh: 0; success.php' );
} else {
$type = "error";
$message = "Problem in Importing CSV Data";
}
}
}
}
}
Just taking a quick look at your code, I have noticed something that is amiss:
if (isset($_POST["import"]))
{
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0)
{
$file = fopen($fileName, "r");
$captabel = true;
$flag = true;
while (($column = fgetcsv($file, 1000, ",")) !== FALSE)
{
if($captabel)
{
$captabel = false;
continue;
}
$celuleNecesare = array(0); <-- Is this being set externally to the code listed here.
foreach ($celuleNecesare as $value)
{
if(trim($column[$value]) == "" || $column[$value] == NULL)
$flag = false;
}
if($flag)
{
$query = "INSERT INTO test
(name ,employee_status, surname, email, address, phone)
VALUES
('" . $column[2] . "','" . $column[7] . "','" . $column[8] . "','" . $column[5] . "','" . $column[0] . "','0" . $column[3] . "')";
$result = mysqli_query($conn, $query);
if (! empty($result))
{
$type = "success";
header( 'refresh: 0; success.php' );
}
else
{
$type = "error";
$message = "Problem in Importing CSV Data";
}
}
}
}
}
You have the line $celuleNecesare = array(0); and then loop through it, but that does nothing in itself.
Your code should be something similar to this:
if (isset($_POST["import"]))
{
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0)
{
$file = fopen($fileName, "r");
$captabel = true;
$flag = true;
// Get the first row as the header row.
$headers = fgetcsv($file, 1000, ",");
// Variables to be used.
$counter = 0;
$nameCol = 0;
$statuscol = 0;
$lastnameCol = 0;
$emailAddressCol = 0;
$employeeAddressCol = 0;
$phoneNumberCol = 0;
foreach($headers as $header)
{
// Name Status Last_name email_address employee_address phone_number
// Lets work through the header row.
switch($header)
{
case 'Name' : $nameCol = $counter;
break;
case 'Status' : $statusCol = $counter;
break;
case 'Last_name': $lastNameCol = $counter;
break;
case 'email_address' : $emailAddressCol = $counter;
break;
case 'employee_address' : $employeeAddressCol = $counter;
break;
case 'phone_number' : $phoneNumberCol = $counter;
break;
default : die("Unknown column, ".$header);
break;
}
$counter++;
}
while (($column = fgetcsv($file, 1000, ",")) !== FALSE)
{
$query = "INSERT INTO test
(name ,employee_status, surname, email, address, phone)
VALUES
('" . $column[$nameCol]."','".$column[$employeeStatusCol]."','".$column[$lastnameCol]."','".$column[$emailAddressCol]."','".$column[$employeeAddressCol]."','0".$column[$phoneNumberCol]."')";
$result = mysqli_query($conn, $query);
// This section below would stop after the first record!!!!!
if (! empty($result))
{
$type = "success";
header( 'refresh: 0; success.php' );
}
else
{
$type = "error";
$message = "Problem in Importing CSV Data";
}
}
}
}
Your IF condition at the end would mean that you are only inserting a single record. Not sure if that is meant, but since you have a while loop for reading in the data, thought there would be many more records.

How to update an image in sql using php

I want to update or set a photo on specific user, when I tried to upload an image, the image is not uploaded on my folder "upload" and the name of the photo (which is a number but 0 e.g: 1.jpg) is inserted in database and the file extension is missing inside the database can someone help me with this
HERE IS MY CODE:
<?php
session_start();
include("../db_connection.php");
$seller_id = $_SESSION['seller_id'];
$trade_name = $_POST ['trade_name'];
$s_address = $_POST ['s_address'];
$opening_time = $_POST ['opening_time'];
$opening_days = $_POST ['opening_days'];
$order_cutoff = $_POST ['order_cutoff'];
$seller_delivery_time = $_POST ['seller_delivery_time'];
$area_covered_delivery = $_POST ['area_covered_delivery'];
$delivery_fee = $_POST ['delivery_fee'];
$extension = pathinfo($_FILES['s_image']['name'], PATHINFO_EXTENSION);
$sql = mysqli_query($db, "UPDATE selling_details
SET
opening_time = '$opening_time',
opening_days = '$opening_days',
order_cutoff = '$order_cutoff',
seller_delivery_time = '$seller_delivery_time',
area_covered_delivery = '$area_covered_delivery',
delivery_fee = '$delivery_fee'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql)
{
$id = mysqli_insert_id($db);
$filename = $id.'.'.$extension;
if(move_uploaded_file($_FILES['s_image']['tmp_name'], 'upload/'.$filename))
{
}
else
{
echo "error occured : " . mysqli_error($db);
}
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '$trade_name',
s_address = '$s_address',
s_image = '$filename'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql2)
{
header('location: seller_menu.php');
}
else
{
echo "error occured : " . mysqli_error($db);
}
}
?>
Try like this... If your field is varchar means it will work. and you need to declare the variable using .[concodinate] operator. Not tested check and let me know.
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '".$trade_name."',
s_address = '".$s_address."',
s_image = '".$filename."'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
Edited:
Try to change like this because if your file upload complete then save into your DB is correct way...In your code is run the second sql2 query if not file upload into the folder.
if ($sql) {
$id = mysqli_insert_id($db);
$filename = $id.'.'.$extension;
if(move_uploaded_file($_FILES['s_image']['tmp_name'], 'upload/'.$filename)) {
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '".$trade_name."',
s_address = '".$s_address."',
s_image = '".$filename."'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql2) {
header('location: seller_menu.php');
}else{
echo "error occured : " . mysqli_error($db);
}
}
} else {
echo "error occured : " . mysqli_error($db);
}
$upload_dir = "upload"; // The directory for the images to be saved in
$upload_path = $upload_dir."/";
$userfile_tmp = $_FILES['s_image'.$i]['tmp_name'];
$filename = basename($_FILES['s_image'.$i]['name']);
$file_Size = $_FILES['s_image']['size'];
$extension = strtolower(substr($filename, strrpos($filename, '.') + 1));
if (empty($extension)) {$error='No extension exist!';}
if(isset($_FILES['s_image']['name']) && $_FILES['s_image']['name']==true && $file_Size >0 && $error=='')
{
$filename = $id.'.'.$extension;
$new_image_location=$upload_path.$filename;
//chmod($new_image_location, 0777);
if(move_uploaded_file($userfile_tmp, $new_image_location))
{
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '$trade_name',
s_address = '$s_address',
s_image = '$filename'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
}else{
echo 'upload folder permission required!!';
//chmod($new_image_location, 0777);
}
}

PHP validate form-datam, and insert to SQL, but img is not required

I am making a ticketing system, and when an user upload a ticket, she/he can upload an image, it is recommended, but not required.
When the user send the ticket with an image, validate is work fine, but without image same validate run and got "file-extension error"....
What am i doing wrong?
PHP code
if ( !isset($_POST['upload_ticket']) ) {
if ( (empty($_POST['type'])) || ($_POST['categ'] == "") || (empty($_POST['title'])) || (empty($_POST['value'])) ) {
echo 'Töltse ki a mezőket!';
} else {
if ( !empty($_FILES['image']) ) {
$user_id = $_SESSION[__SITE_ID__]['users']['id'];
$type = $_POST['type'];
$categ = $_POST['categ'];
$title = trim($_POST['title']);
$title = ucfirst($title);
$title = htmlspecialchars($title, ENT_QUOTES, "UTF-8");
$value = trim($_POST['value']);
$value = ucfirst($value);
$value = htmlspecialchars($value, ENT_QUOTES, "UTF-8");
$reg_date = date("Y-m-d H:i:s");
if ( is_dir('Pictures/' . date('Ymd') . '/') ) {
$path = 'Pictures/' . date('Ymd') . '/';
} else {
$path = mkdir('Pictures/' . date('Ymd') . '/');
}
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_tmp = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
$image_ext = strtolower(end(explode('.',$image_name)));
$expensions = array('jpg', 'jpeg', 'png', 'gif');
$target_file = $path . basename($image_name);
$imgext = pathinfo($target_file,PATHINFO_EXTENSION);
if ( in_array($image_ext,$expensions) === false){
echo 'JPG, JPEG, PNG, GIF megengedett';
} else if ( $image_size > 2097152 ) {
echo 'Túl nagy a kép! Max 2 MB';
} else {
move_uploaded_file($image_tmp, $target_file);
$userquery = "INSERT INTO [gyakornok].[dbo].[t_tickets]";
$userquery .= " (user_id, type, categ_id, status_id, title, value, image, reg_date)";
$userquery .= " VALUES ('$user_id', '$type', (SELECT id FROM t_status WHERE value='Aktív') , '$categ', '$title', '$value', '$target_file','$reg_date')";
$userquery = sqlsrv_query($conn, $userquery);
echo 'Sikeresen elküldte a bejegyzését';
}
} else {
$user_id = $_SESSION[__SITE_ID__]['users']['id'];
$type = $_POST['type'];
$categ = $_POST['categ'];
$title = trim($_POST['title']);
$title = ucfirst($title);
$title = htmlspecialchars($title, ENT_QUOTES, "UTF-8");
$value = trim($_POST['value']);
$value = ucfirst($value);
$value = htmlspecialchars($value, ENT_QUOTES, "UTF-8");
$reg_date = date("Y-m-d H:i:s");
$userquery = "INSERT INTO [gyakornok].[dbo].[t_tickets]";
$userquery .= " (user_id, type, categ_id, status_id, title, value, reg_date)";
$userquery .= " VALUES ('$user_id', '$type', (SELECT id FROM t_status WHERE value='Aktív') , '$categ', '$title', '$value', '$reg_date')";
$userquery = sqlsrv_query($conn, $userquery);
echo 'Sikeresen elküldte a bejegyzését';
}
}
}
I beleive this is the correct way of handling what you need...
I changed if (!isset($_POST['upload_ticket']) ) to if (isset($_POST['upload_ticket']) )so the form is actually detected if submitted.
Then added elseif( empty($_FILES['image']) ) so the form will be submitted normally if there is no image.
<?
if (isset($_POST['upload_ticket']) ) {
if ( (empty($_POST['type'])) || ($_POST['categ'] == "") || (empty($_POST['title'])) || (empty($_POST['value'])) ) {
echo 'Töltse ki a mezőket!';
} else {
if ( !empty($_FILES['image']) ) {
$user_id = $_SESSION[__SITE_ID__]['users']['id'];
$type = $_POST['type'];
$categ = $_POST['categ'];
$title = trim($_POST['title']);
$title = ucfirst($title);
$title = htmlspecialchars($title, ENT_QUOTES, "UTF-8");
$value = trim($_POST['value']);
$value = ucfirst($value);
$value = htmlspecialchars($value, ENT_QUOTES, "UTF-8");
$reg_date = date("Y-m-d H:i:s");
if ( is_dir('Pictures/' . date('Ymd') . '/') ) {
$path = 'Pictures/' . date('Ymd') . '/';
} else {
$path = mkdir('Pictures/' . date('Ymd') . '/');
}
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_tmp = $_FILES['image']['tmp_name'];
$image_type = $_FILES['image']['type'];
$image_ext = strtolower(end(explode('.',$image_name)));
$expensions = array('jpg', 'jpeg', 'png', 'gif');
$target_file = $path . basename($image_name);
$imgext = pathinfo($target_file,PATHINFO_EXTENSION);
if ( in_array($image_ext,$expensions) === false){
echo 'JPG, JPEG, PNG, GIF megengedett
';
} else if ( $image_size > 2097152 ) {
echo 'Túl nagy a kép! Max 2 MB
';
} else {
move_uploaded_file($image_tmp, $target_file);
$userquery = "INSERT INTO [gyakornok].[dbo].[t_tickets]";
$userquery .= " (user_id, type, categ_id, status_id, title, value, image, reg_date)";
$userquery .= " VALUES ('$user_id', '$type', (SELECT id FROM t_status WHERE value='Aktív') , '$categ', '$title', '$value', '$target_file','$reg_date')";
$userquery = sqlsrv_query($conn, $userquery);
echo 'Sikeresen elküldte a bejegyzését
';
}
} elseif( empty($_FILES['image']) ) {
$user_id = $_SESSION[__SITE_ID__]['users']['id'];
$type = $_POST['type'];
$categ = $_POST['categ'];
$title = trim($_POST['title']);
$title = ucfirst($title);
$title = htmlspecialchars($title, ENT_QUOTES, "UTF-8");
$value = trim($_POST['value']);
$value = ucfirst($value);
$value = htmlspecialchars($value, ENT_QUOTES, "UTF-8");
$reg_date = date("Y-m-d H:i:s");
$userquery = "INSERT INTO [gyakornok].[dbo].[t_tickets]";
$userquery .= " (user_id, type, categ_id, status_id, title, value, reg_date)";
$userquery .= " VALUES ('$user_id', '$type', (SELECT id FROM t_status WHERE value='Aktív') , '$categ', '$title', '$value', '$reg_date')";
$userquery = sqlsrv_query($conn, $userquery);
echo 'Sikeresen elküldte a bejegyzését';
}
}
}
?>
Correct me if I'm wrong please, and I will double check.

I want to upload multiple image name in a same row using PHP MYSQL

Here is my code
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++)
{
// get the image mime type
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
if (in_array($image_mime, $valid_image_check))
{
$folderName = "uploads/";
$ext = explode("/", strtolower($image_mime));
$ext = strtolower(end($ext));
$filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
// if user upload a file abc,jpg, it will convert it to 291905_1399918178.jpg based on random number and time.
$filepath = $folderName . $filename;
if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath))
{
echo "fail uplaod";
} else {
$smsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> uploaded successfully. <br>";
$magicianObj = new imageLib($filepath);
$magicianObj->resizeImage(100, 100);
$magicianObj->saveImage($folderName . 'thumb/' . $filename, 100);
}
} else {
echo "not image";
}
}
and MySQL query is
$sql = "INSERT INTO properties
(agent_id, property_name, category, location,
property_type, search_radius, price, bed_rooms,
bath_rooms, commercial_type, area, address,
description, image_name, date_added)
VALUES
('$agent_id', '$property_name', '$listing_for', '$city',
'$property_type', '$area', '$price', '$beds',
'$baths', '$commercial_type', '$area_sf', '$address',
'$description', '".$filename."', now() )" ;
so here I need to Insert my all $filename values in a single row.
But when I run this script only the last $filename is inserted into DB.
How can I insert my all values of $filename from for loop in DB in a single row.
You'll need to use a persistent array for this.
$fileNames = array();
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++)
{
// get the image mime type
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
if (in_array($image_mime, $valid_image_check))
{
$folderName = "uploads/";
$ext = explode("/", strtolower($image_mime));
$ext = strtolower(end($ext));
$filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
// if user upload a file abc,jpg, it will convert it to 291905_1399918178.jpg based on random number and time.
$filepath = $folderName . $filename;
if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath))
{
echo "fail uplaod";
} else {
$smsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> uploaded successfully. <br>";
$magicianObj = new imageLib($filepath);
$magicianObj->resizeImage(100, 100);
$magicianObj->saveImage($folderName . 'thumb/' . $filename, 100);
$fileNames[] = $filepath;
}
} else {
echo "not image";
}
}
And then in your SQL:
$images = rtrim(implode(',', $fileNames), ',');
$sql = "INSERT INTO properties
(agent_id, property_name, category, location,
property_type, search_radius, price, bed_rooms,
bath_rooms, commercial_type, area, address,
description, image_name, date_added)
VALUES
('$agent_id', '$property_name', '$listing_for', '$city',
'$property_type', '$area', '$price', '$beds',
'$baths', '$commercial_type', '$area_sf', '$address',
'$description', '$images', now() )" ;
This will insert a comma separated list of filenames into the DB.
You may want to have a look at prepared statements from the looks of your query.
You should probably use another table for something like this, which attaches to the property ID.
image_id | image_url | property_id
SELECT `image_url` FROM `property_images` WHERE `property_id` = :property_id
Something along those lines, as has been commented this is a bad way of doing things.

How to do I send a timestamped image to MySQL with an edit multiple image form?

How do i get a unique image to MySQL and still be able to edit just one image at a time? I only have the ability to update 4 images at once with a unique id or I can edit the images seperatly and have them update without a unique id.
<?php
require_once('storescripts/connect.php');
mysql_select_db($database_phpimage,$phpimage);
$uploadDir = 'upload/';
if(isset($_POST['upload']))
{
foreach ($_FILES as $file)
{
$fileName = $file['name'];
$tmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileType = $file['type'];
if ($fileName != ""){
$filePath = $uploadDir;
$fileName = str_replace(" ", "_", $fileName);
//Split the name into the base name and extension
$pathInfo = pathinfo($fileName);
$fileName_base = $pathInfo['fileName'];
$fileName_ext = $pathInfo['extension'];
//now we re-assemble the file name, sticking the output of uniqid into it
//and keep doing this in a loop until we generate a name that
//does not already exist (most likely we will get that first try)
do {
$fileName = $fileName_base . uniqid() . '.' . $fileName_ext;
} while (file_exists($filePath.$fileName));
$file_names [] = $fileName;
$result = move_uploaded_file($tmpName, $filePath.$fileName);
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$fileinsert[] = $filePath;
}
}
$mid = mysql_real_escape_string(trim($_POST['mid']));
$cat = mysql_real_escape_string(trim($_POST['cat']));
$item = mysql_real_escape_string(trim($_POST['item']));
$price = mysql_real_escape_string(trim($_POST['price']));
$about = mysql_real_escape_string(trim($_POST['about']));
$fields = array();
$values = array();
$updateVals = array();
for($i = 0; $i < 4; $i++)
{
$values[$i] = isset($file_names[$i]) ? mysql_real_escape_string($file_names[$i]) : '';
if($values[$i] != '')
{
$updateVals[] = "{$fields[$i]} = '{$values[$i]}'";
}
}
$updateNames = '';
if(count($updateVals))
{
$updateNames = ", " . implode(', ', $updateVals);
}
$update = "INSERT INTO image
(mid, cid, item, price, about, name1, name2, name3, name4)
VALUES
('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]')
ON DUPLICATE KEY UPDATE
cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames";
$result = mysql_query($update) or die (mysql_error());
Within your foreach ($_FILES as $file) { loop you are renaming and saving the uploaded file but you are using the original filenames when inserting into the db. You need to store the renamed files in the db. After your do ... while loop assign the new filename to an array -
do {
$fileName = $fileName_base . uniqid() . '.' . $fileName_ext;
} while (file_exists($filePath.$fileName));
$file_names[] = $fileName;
then modify your for loop to -
for($i = 0; $i < 4; $i++)
{
$values[$i] = isset($filenames[$i]) ? mysql_real_escape_string($filenames[$i]) : '';
if($values[$i] != '') {
$updateVals[] = 'name' . ($i + 1) . " = '{$values[$i]}'";
}
}
and finally, update your update statement to -
$update = "INSERT INTO image
(mid, cid, item, price, about, name1, name2, name3, name4)
VALUES
('$mid', '$cat', '$item', '$price', '$about', '$values[0]', '$values[1]', '$values[2]', '$values[3]')
ON DUPLICATE KEY UPDATE
cid = '$cat', item = '$item', price = '$price', about = '$about' $updateNames";

Categories