How to update an image in sql using php - 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);
}
}

Related

count messages that sent by users in my chat

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>

upload all fields with the image file upload optional PHP MySQLI

I have searched far and wide and cannot find an answer to my question in terms that I can understand. I am trying to make my code upload all text input fields and if not image is in the file input, then upload all except the image and upload all including the image when an image is present. Below is my working code for when an image is present. All help will be greatly appreciated.
<?php
session_start();
error_reporting(E_ALL);
include_once 'dbconnect.php';
$userID = $_SESSION['usr_id'];
if(!empty($_FILES["uploadedimage"]["tmp_name"])) {
$eTitle = mysqli_real_escape_string($con, $_POST['etitle']);
$eDate=mysqli_real_escape_string($con, $_POST['edate']);
$eDesc=mysqli_real_escape_string($con, $_POST['edesc']);
$file_tmp = $_FILES['uploadedimage']['tmp_name'];
$file_ext = strtolower(end(explode('.',$_FILES['uploadedimage']['name'])));
$date = date("d-m-Y");
$imagename = $date."-".time().".".$file_ext;
$target_path = "event_images/".$imagename;
$move = move_uploaded_file($file_tmp, $target_path);
if($move) {
if($_FILES['uploadedimage']===false){
$not = "NULL";
}ELSE{
$not = $imagename;
}
$sql =mysqli_query($con, "INSERT INTO `events` (eventID,eventImage,eventTitle,eventDate,eventDescription) values (NULL,'".$not."','".$eTitle."','".$eDate."','".$eDesc."')");
$db = mysqli_query($sql, $con);
$msg = "Song has been uploaded successfully";
header("Location: websiteeditor.events.php");
}
else {
$msg = "Not uploaded because of error #".$_FILES["file"]["error"];
}
}
else {
$msg = "Failed to Upload<br/>Not uploaded because of error #".$_FILES["file"]["error"];
}
?>
<?=$msg;?>
Following code should work the way you need it.
<?php
session_start();
error_reporting(E_ALL);
include_once 'dbconnect.php';
$userID = $_SESSION['usr_id'];
$eTitle = mysqli_real_escape_string($con, $_POST['etitle']);
$eDate = mysqli_real_escape_string($con, $_POST['edate']);
$eDesc = mysqli_real_escape_string($con, $_POST['edesc']);
$date = date("d-m-Y"); // where is this used?
$not = null;
if (!empty($_FILES["uploadedimage"]["tmp_name"])) {
$file_tmp = $_FILES['uploadedimage']['tmp_name'];
$file_ext = strtolower(end(explode('.', $_FILES['uploadedimage']['name'])));
$imagename = $date . "-" . time() . "." . $file_ext;
$target_path = "event_images/" . $imagename;
$move = move_uploaded_file($file_tmp, $target_path);
if ($move) {
$not = $imagename;
} else {
$msg = "Not uploaded because of error #" . $_FILES["file"]["error"];
}
}
$sql = mysqli_query($con, "INSERT INTO `events` (eventID,eventImage,eventTitle,eventDate,eventDescription) values (NULL,'" . $not . "','" . $eTitle . "','" . $eDate . "','" . $eDesc . "')");
$db = mysqli_query($sql, $con);
$msg = "Song has been uploaded successfully";
header("Location: websiteeditor.events.php");
?>

The Filename of the image I'm uploading is not changing

Evertime I upload a picture, the FILENAME is NOT CHANGING the static value(filename) that is inserting in database is always "0.png" I don't know how is that happening, Please Help me how to fix this problem.
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))
{
$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);
}
}
?>
The function mysqli_insert_id returns the id of the row you just inserted into your database, and since you don't insert anything (you just update) the value the function returns is 0, so the name of your image is $id.'.'.$extension ==> 0.png.
Since you update the seller_id, and you have it inside $_SESSION['seller_id'], you can use it in your code:
$filename = $_SESSION['seller_id'].'.'.$extension;

error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE

<!doctype html>
<html>
<head>
<title>Pengubahan Data Pemain</title>
<style>
label {
float: left;
width: 100px;
}
</style>
</head>
<body>
<h1>Pengubahan Data Pemain</h1>
<?php
$kunci = isset($_GET["kunci"]) ?
trim($_GET["kunci"]) : "";
$pesan = isset($_GET["pesan"]) ?
trim($_GET["pesan"]) : "";
if ($kunci !== "") {
// Lakukan koneksi database
$koneksi = new mysqli("localhost", "root",
"syamsunisramani", "dbartt");
if (!$koneksi)
die("Koneksi gagal");
// Proses SQL
$sql = "SELECT * FROM pemain WHERE id_artt = '" .
$kunci . "';";
if ($hasil = $koneksi->query($sql))
if ($hasil->num_rows > 0) {
print("<form action=\"pemsimp.php\" method=\"post\">");
print("<fieldset>");
while ($baris = $hasil->fetch_array()) {
print("<p>\n");
print("<label>ID ARTT:</label>\n");
print("<input type=\"hidden\" name=\"id-artt\"");
print(" value=\"$kunci\">\n");
print("<input type=\"text\" name=\"kunci\"");
print(" value=\"$kunci\">\n");
print("</p>\n");
print("<p>\n");
print("<label>Nama Pemain:</label>\n");
print("<input type=\"text\" name=\"nama-pemain\"");
print(" value=\"$baris[1]\">\n");
print("</p>\n");
print("<p>\n");
print("<label>Klub Pemain:</label>\n");
print("<input type=\"text\" name=\"klub-pemain\"");
print(" value=\"$baris[2]\">\n");
print("</p>\n");
}
print("<input type=\"submit\" value=\"Simpan\">\n");
print("</fieldset>\n");
print("</form>\n");
}
else {
print("Data tidak ditemukan<br>");
$pesan = "";
}
else {
print("Gagal memproses. Kesalahan: " .
$koneksi->error . "<br>");
$pesan = "";
}
// Tutup koneksi
$koneksi->close();
}
else
print("Salah pemakaian");
// Tampilkan pesan kesalahan
if ($pesan !== FALSE)
print($pesan);
?>
</body>
</html>
//pemsimp.php
<?php
$id_artt = isset($_POST["id-artt"]) ?
trim($_POST["id-artt"]) : "";
$nama_pemain = $_POST["nama-pemain"];
$klub_pemain = $_POST["klub-pemain"];
if (empty($id_artt)) {
die("Salah pemanggilan");
}
// Lakukan koneksi database
$koneksi = new mysqli("localhost", "root",
"syamsunisramani", "dbartt");
if (!$koneksi)
die("Koneksi gagal");
// Proses SQL
$sql = "UPDATE pemain SET " .
"nama_pemain = '$nama_pemain', " .
"klub_pemain = '$klub_pemain', " .
"WHERE id_artt = '" . $id_artt . "';";
$pesan = "";
if ($hasil = $koneksi->query($sql))
$pesan = "Data pemain '$nama_pemain' telah disimpan";
else
$pesan = "Gagal menyimpan. Kesalahan: " . $koneksi->error;
// Tutup koneksi
$koneksi->close();
// Redirection
header("location: ubahpem.php?kunci=$id_artt&pesan=$pesan");
?>
-When I update the database 'dbartt' by entering 'nama_pemain' or klub_pemain value with new value.
-It shows the following error. Please fix my code.
-error : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server -version for the right syntax to use near 'WHERE id_artt = '11:22:33:44:55:66'' at line 1
Change this
$sql = "SELECT * FROM pemain WHERE id_artt = '" . $kunci . "';";
to this,
$sql = "SELECT * FROM pemain WHERE id_artt = '" . $kunci . "'";
There are a few mistake that I found (an additional ',' and a ';') and I think that may be causing the problem.
Replace your query code like this
$sql = "UPDATE pemain SET " .
"nama_pemain = '$nama_pemain', " .
"klub_pemain = '$klub_pemain' " .
"WHERE id_artt = '" . $id_artt . "'";
Another thing is that make sure that the type of 'id_artt' column is in a format that can accept the values like "11:22:33:44:55:66"
Your where condition should be like this.
$sql = "SELECT * FROM pemain WHERE id_artt = '".$kunci ."' ";
You can write that this way...
$sql = "
UPDATE pemain
SET nama_pemain = '$nama_pemain'
, klub_pemain = '$klub_pemain'
WHERE id_artt = $id_artt;
";
The penultimate semi-colon isn't necessary but I like to include it so I can just copy and paste the echo into a MySQL CLI for testing.
with heredoc query
$sql = <<<SQL
UPDATE pemain
SET nama_pemain = '$nama_pemain'
, klub_pemain = '$klub_pemain'
WHERE id_artt = $id_artt
SQL;
If we decide it turns out to be turning on the ", / comma" sign. Because according to the request for renewal permission, there can be no commas before WHERE, the comma is only used if there are still data fields to be changed. Here's the correct script:
"UPDATE pemain SET " .
"nama_pemain = '$nama_pemain', " .
"klub_pemain = '$klub_pemain'" .
"WHERE id_artt = '" . $id_artt . "';";
or
"UPDATE pemain SET nama_pemain = '$nama_pemain', klub_pemain = '$klub_pemain' WHERE id_artt = '$id_artt'";

Why is this code returning a line break before the echo?

So I have this login php script that I am using and it works fine on one server (returns "success" || "invalid login") and then this other server it breaks because it returns a line break and then "success" or "invalid login"
My guess is a php.ini setting. I am just not sure which one.
<?php
include("../config.php");
include("../connect.php");
$adminCheck = mysql_query("SELECT * FROM admins WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($adminCheck) == 1)
{
$result = mysql_fetch_array($adminCheck);
$_SESSION['user']['level'] = "admin";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
echo "success";
}
else
{
$clientCheck = mysql_query("SELECT * FROM clients WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($clientCheck) == 1)
{
$result = mysql_fetch_array($clientCheck);
$_SESSION['user']['level'] = "client";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
$_SESSION['user']['client'] = $result['client'];
echo "success";
}
else
{
echo "invalid login";
}
}
?>
I'd bet you a coke that connect.php or config.php contain a \n (or \r\n) before or after their <?php ?> parts.
This is most likely due to your includes. The code you posted has no reason to have one, and there is no php.ini setting that I'm aware of to add such.
Post your config and connect (with username/pw hidden) for us to help further.
The code displayed does not indicate the occurrence of a line-break.
On a side note since you are only outputting one value from your booleans then you could initialize a variable to hold the response and then only echo the response once:
<?php
include("../config.php");
include("../connect.php");
$response = 'success';
$adminCheck = mysql_query("SELECT * FROM admins WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($adminCheck) == 1)
{
$result = mysql_fetch_array($adminCheck);
$_SESSION['user']['level'] = "admin";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
}
else
{
$clientCheck = mysql_query("SELECT * FROM clients WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($clientCheck) == 1)
{
$result = mysql_fetch_array($clientCheck);
$_SESSION['user']['level'] = "client";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
$_SESSION['user']['client'] = $result['client'];
}
else
{
$response = "invalid login";
}
}
echo $response;
?>

Categories