File path with '/' is not inserting in DB - php

I need to check duplicate files from a path and need to insert the file name in a table if it is new and then insert all records of it accordingly into another table. Do not insert or step forward if file already exists.
Here is my code where i can't bring the file path with '/' into the DB. Can anyone assist? Thanks in advance.
File Path with '/' is not passing using $open = fopen('$cont[$x]','r');
<?php
//include ("connection.php");
$conn = new mysqli('localhost','root','','demo');
$path = _DIR_ . DIRECTORY_SEPARATOR ."*.{txt}";
$cont = glob($path, GLOB_BRACE);
//print_r($content);
$arrlength = count($cont);
for($x = 0; $x < $arrlength; $x++){
// $sql = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
$dup = mysqli_query($conn,"SELECT * FROM file_record WHERE file_name = '$cont[$x]' ");
if(mysqli_num_rows($dup)>0)
{
echo "File already Exists";
}
else {
$insert = "INSERT INTO `file_record` (`file_name`) VALUES ('$cont[$x]') ";
// $conn->query($insert);
if (mysqli_query($conn,$insert)) {
$open = fopen('$cont[$x]','r');
while (!feof($open))
{
$content = fgets($open);
$carry = explode(",",$content);
list($name,$city,$postcode,$job_title) = $carry;
$sql = "INSERT INTO `employee` (`name`, `city`, `postcode`, `job_title`) VALUES ('$name','$city','$postcode','$job_title')";
$conn->query($sql);
}
fclose($open);
echo 'inserted';
} else {
echo 'Not inserted';
}
}
}
?>

Related

php error file not upload on this api code

this api code is in php and server is in digitalocen and ubuntu 16.04.
we are try upload file but every time we show the error param missing .
we are try thi change folder permission 777 but nothing steel file is not uploading.the same code working 2 days ego but now code is not working.
<?php
include('conn.php');
include('function.php');
$user_id = $_POST['user_id'];
$dute_user_id = $_POST['dute_user_id'];
$music_id = $_POST['music_id'];
$music = $_FILES['music']['name'];
$hashtags = $_POST['hashtags'];
$video = $_FILES['video']['name'];
$gif = $_FILES['gif']['name'];
$microtime = round(microtime(true) * 1000);
validate_user($con, $user_id);
if($user_id=="" || $video=="" || $gif=="" || ($music_id=="" && $music=="")){
$res['status'] = 0;
$res['msg'] = "param missing";
echo json_encode($res);
die;
}
else{
$user_data = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM `user` WHERE `user_id`='".$user_id."'"));
if($music_id=="" && $music!=""){
$music = basename($_FILES["music"]["name"]);
$fileType = strtolower(pathinfo($music,PATHINFO_EXTENSION));
$music_file = "music/" . $microtime .".". $fileType;
move_uploaded_file($_FILES["music"]["tmp_name"], $music_file);
$title = "original - " . $user_data['user_name'] . rand(1111,9999);
mysqli_query($con, "INSERT INTO `music` (`title`, `user_id`, `m_link`, `time`) VALUES ('".$title."', '".$user_id."', '".$music_file."', '".$microtime."')");
$music_id = mysqli_insert_id($con);
mysqli_query($con, "INSERT INTO `m_category` (`music_id`, `category_id`) VALUES ('".$music_id."', '1')");
}
if($video!=""){
$video = basename($_FILES["video"]["name"]);
$fileType = strtolower(pathinfo($video,PATHINFO_EXTENSION));
$video_file = "video/" . $microtime .".". $fileType;
move_uploaded_file($_FILES["video"]["tmp_name"], $video_file);
}
if($gif!=""){
$gif = basename($_FILES["gif"]["name"]);
$fileType = strtolower(pathinfo($gif,PATHINFO_EXTENSION));
$gif_file = "gif/" . $microtime .".". $fileType;
move_uploaded_file($_FILES["gif"]["tmp_name"], $gif_file);
}
mysqli_query($con, "INSERT INTO `post`(`music_id`, `v_url`, `user_id`, `dute_user_id`, `gif_url`, `time`) VALUES ('".$music_id."', '".$video_file."', '".$user_id."', '".$dute_user_id."', '".$gif_file."', '".$microtime."')");
$post_id = mysqli_insert_id($con);
if($dute_user_id!=""){
mysqli_query($con, "INSERT INTO `post_hashtag`(`post`, `hashtag`) VALUES ('".$post_id."','duet')");
}
if($hashtags!=""){
$hashtag = explode("#", $hashtags);
for($i=0; $i < count($hashtag); $i++) {
mysqli_query($con, "INSERT INTO `post_hashtag`(`post`, `hashtag`) VALUES ('".$post_id."','".$hashtag[$i]."')");
}
}
$res['status'] = 1;
$res['msg'] = "Post Uploaded Successfully";
echo json_encode($res);
die;
}
?>
result
{"status":0,"msg":"param missing"}
here is postman error image

Duplicate entries in SQL?

I keep getting duplicate posts in the SQL DB.
This is the code I am using to create the table and insert data into the DB..
$query = "SELECT * FROM '.$cname.' WHERE name='$itemname' and price='$price'";
$result = mysqli_query($db, $query);
$count = mysqli_num_rows($result);
if($count == 0){
//insert doesn't exist, continue
//insert sizes
$list = "";
$number = count($sizes);
$num = 0;
if($usesize == 'yes'){
$num = 1;
if($number > 0){
for($i=0; $i<$number; $i++){
if(trim($_POST["size"][$i] != '')){
if(empty($list)){
$list = $_POST["size"][$i];
}else{
$list .= ",".$_POST["size"][$i];
}
}
}
echo $list;
}
$quantitylist = "";
$quantitynumber = count($quantity);
if($quantitynumber > 0){
for($a=0; $a<$quantitynumber; $a++){
if(trim($_POST["quantity"][$a] != '')){
if(empty($quantitylist)){
$quantitylist = $_POST["quantity"][$a];
}else{
$quantitylist .= ",".$_POST["quantity"][$a];
}
}
}
echo $quantitylist;
}
}else{
$num = 0;
}
$colorlist = "";
$colornumber = count($colors);
$cnum = 0;
if($usecolors == 'yes'){
$cnum = 1;
if($colornumber > 0){
for($i=0; $i<$colornumber; $i++){
if(trim($_POST["colors"][$i] != '')){
if(empty($colorlist)){
$colorlist = $_POST["colors"][$i];
}else{
$colorlist .= ":".$_POST["colors"][$i];
}
}
}
echo $colorlist;
}
}else{
$cnum = 0;
}
$query = "INSERT INTO ".$cname." (name, description, imgpath, price, sold, usesize, usecolors) VALUES ('$itemname', '$description', '$insertloc"."$name', '$price', '0', '$num', '$cnum')";
if(mysqli_query($db, $query)){
//inserted successfully
echo "Inserted successfully!";
}else{
$uploadOk = 0;
echo mysqli_error($db);
}
$conn = mysqli_connect('localhost', 'grampmkn_gramsandpops', 'Grams123', 'grampmkn_shop_quantity');
if($conn){
$query = "CREATE TABLE `".$itemname."` (
id int NOT NULL AUTO_INCREMENT,
size varchar(500),
color varchar(500),
quantity int(100),
PRIMARY KEY(id),
UNIQUE(size)
);";
$array = explode(',', $list);
if(mysqli_query($conn, $query)){
mysqli_select_db($conn, $name);
$array = explode(',', $list);
foreach($array as $value){
$arrays = explode(':', $colorlist);
foreach($arrays as $values){
$arrays1 = explode(',', $quantitylist);
foreach($arrays1 as $values1){
$query = "INSERT INTO `".$itemname."` (size, color, quantity) VALUES ('$value', '$values', '$values1')";
if(mysqli_query($conn, $query)){
echo "Successfully inserted data into grampmkn_shop_quantity!";
}else{
echo mysqli_error($conn);
}
}
}
}
}else{
echo "Could not create table";
}
}else{
echo "Could not connect to shop quantity database!";
echo mysqli_errno($conn);
}
}else{
//insert already exists
echo "Insert already exists!";
$uploadOk = 0;
}
Image from DB.
If I remove the nested loops, then how would I get all the data in the arrays to insert into the sql database.
I am only creating the table once, I am just inserting multiple times to get all the data into the db.
Any help is appreciated.

PHP How to read specific words and lines then add to MySQL database

I try to read every word after this word #EXTINF:-1
and the next line from the local file and subsequently add the result to MySQL if it does not exist.
The contents of the file looks like this:
#EXTM3U
#EXTINF:-1,name1
http://www.name1
#EXTINF:-1,name2
http://www.name2
#EXTINF:-1,name3
http://www.name3
#EXTINF:-1,name4
http://www.name4
And my code:
$file = file("file.m3u);
array_shift($file);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$getname[] = substr($row, $pos + 1);
} else {
$geturl[] = $row;
} } }
$count = count($getname);
for($i=0; $i < $count; $i++){
$name = $getname[$i];
$url = $geturl[$i];
if (empty($name)) { exit; };
if (empty($url)) { exit; }
$get_user = mysql_query("select * from users where (name = '$name')");
$show_user = mysql_fetch_array($get_user);
$userid = $show_user['userid'];
$get_url = mysql_query("select * from urls where url = '$url'");
$show_url = mysql_fetch_array($get_url);
$urlid = $show_url['urlid'];
if (empty($userid) && empty($urlid)) {
$add_user = "INSERT INTO users(name)
VALUES('$name')";
mysql_query($add_user);
$userid = mysql_insert_id();
$add_url = "INSERT INTO urls(userid, url)
VALUES('$userid', '$url')";
mysql_query($add_url);
$urlid = mysql_insert_id();
}
}
My code cannot read file correctly, because when I try check the line that I had read from file, it does not work.
The info that I try to read:
name = name1
url = http://www.name1
is for every user.
This might have something to do with it
$file = file("file.m3u);
It should be
$file = file("file.m3u");

uploading 4 files at a time in a single database insert query

i want to upload 4 file at a time in a single insert database query how to to that? below is my code
$name_array = $_FILES['files']['name'];
$tmp_name_array = $_FILES['files']['tmp_name'];
$type_array = $_FILES['files']['type'];
$size_array = $_FILES['files']['size'];
for ($i=0; $i<count($tmp_name_array); $i++ ){
if(move_uploaded_file($tmp_name_array[$i],"uploads/".$name_array[$i])){
$query = "INSERT INTO photos (`file_name`, `file_name1`,`file_name2`,`file_name3` `file_type`,`size`,`caption`) VALUES('$name_array[$i]',$name_array[$i]',$name_array[$i]',$name_array[$i]','$ty pe_array[$i]','$size_array[$i]','$caption[$i]') ";
mysql_query($query);
var_dump($query);
echo "The file $name_array[$i] has been upload ";
} else {
echo "The file $name_array[$i] has not been upload ";
}
}
First of all, don't use deprecated mysql_ functions. Change them to mysqli_ or PDO.
Now to insert multiple entries to database using single query, you can use this syntax:
INSER INTO table_name (columnName1, columnName2, ...) VALUES
(val1_1, val1_2, ...),
(val2_1, val2_2, ...),
...
So with your code you can do:
$query = "INSERT INTO photos (`file_name`, `file_name1`,`file_name2`,`file_name3` `file_type`,`size`,`caption`) VALUES ";
$inserts = [];
for ($i = 0; $i < count($tmp_name_array); $i++) {
if (move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])) {
$inserts[] = "('{$name_array[$i]}', '{$name_array[$i]}', '{$name_array[$i]}', '{$name_array[$i]}', '{$type_array[$i]}', '{$size_array[$i]}', '{$caption[$i]}')";
}
}
if (!empty($inserts)) {
mysql_query($query.implode(", ", $inserts));
} else {
echo "No files to be uploaded and saved";
}
But still, change this to prepared statement (it will eliminate missing ' before parameters).
from your code above i think you are trying to do something like this. here is a little piece of code to upload multiple files.
$file_arr= array();
for($i=0,$j=0; $i<count($_FILES['userfile']['name']); $i++)
{
if(isset($_FILES['userfile']['name'][$i]) && $_FILES['userfile']['name'][$i] != "")
{
$file_arr[$j] = array();
$file_arr[$j]['name'] = $_FILES['userfile']['name'][$i];
$file_arr[$j]['size'] = $_FILES['userfile']['size'][$i];
$file_arr[$j]['type'] = $_FILES['userfile']['type'][$i];
$file_arr[$j]['tmp_name'] = $_FILES['userfile']['tmp_name'][$i];
$j++;
}
}
if(count($file_arr) > 0){
$file_location = 'uploads/files/';
for($i=0; $i<count($file_arr); $i++)
{
if(move_uploaded_file($file_arr[$i]['tmp_name'],$file_location.$file_arr[$i]['name'])){
$msg = "uploaded successfully";
$query="INSERT INTO photos (`file_name`, `file_type`,`size`,`caption`) VALUES('$file_arr['name']','$file_arr['type']','$file_arr['size']','$caption') ";
$q2 =mysql_query($sql2) or die(mysql_error());
}
}
}

PHP and MySQL Error "Column count doesn't match value count at row 1"

So i am having this issue. The code is for art gallery calendar. The code has worked for this day but now it has broken down. I wrote it about 1-2 months ago and now they contacted me that something is wrong. Here is the code
<?php
require('config.php');
if(isset($_POST['lisaa_pvm'])) {
$alkupvm = mysql_real_escape_string(strtotime(str_replace('/','-',$_POST['alkupvm'])));
$loppupvm = mysql_real_escape_string(strtotime(str_replace('/','-',$_POST['loppupvm'])));
$muuta = mysql_real_escape_string($_POST['muuta']);
$result = mysql_query("INSERT INTO kipina_kalenteri VALUES ('','$alkupvm','$loppupvm','','','','','$muuta')") or die (mysql_error());
$tapahtuma_id = mysql_insert_id();
header('location: lisaa_tapahtuma.php?tid='.$tapahtuma_id);
}
if(isset($_POST['lisaa_tapahtuma'])) {
// siivotaan syƶtteet
foreach ($_POST as $key => $value) {
mysql_real_escape_string($value);
${"$key"} = $value;
}
$url = ROOT.'/files/';
if($_FILES['kuva1']['size'] > 0) {
$target = $url . $_FILES['kuva1']['name'];
if(move_uploaded_file($_FILES['kuva1']['tmp_name'], $target)) {
$kuva[] = "kuva_1 = '".basename( $_FILES['kuva1']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if($_FILES['kuva2']['size'] > 0) {
$target = $url . basename( $_FILES['kuva2']['name']);
if(move_uploaded_file($_FILES['kuva2']['tmp_name'], $target)) {
$kuva[] = "kuva_2 = '".basename( $_FILES['kuva2']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if($_FILES['kuva3']['size'] > 0) {
$target = $url . basename( $_FILES['kuva3']['name']);
if(move_uploaded_file($_FILES['kuva3']['tmp_name'], $target)) {
$kuva[] = "kuva_3 = '".basename( $_FILES['kuva3']['name'])."'";
} else{
echo "There was an error uploading the file ".$target.", please try again!<br>";
}
}
if(isset($kuva)) {
$kuvat = ", ".implode(',',$kuva);
}
if(isset($sama) AND $sama != '') {
$update = "UPDATE kipina_kalenteri SET $paikka = $sama $kuvat WHERE id = $kalenteri";
mysql_query($update) or die (mysql_error());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
} elseif(isset($update)) {
$update = "UPDATE kipina_tapahtuma SET
taiteilija = '$taiteilija',
nimi = '$nimi',
kuvaus = '$kuvaus',
kuvaus = '$lyhyt_kuvaus'
$kuvat
WHERE
id = $update";
$result = mysql_query($update) or die (mysql_query());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
} else {
$insert = mysql_query("INSERT INTO kipina_tapahtuma VALUES ('','$taiteilija','$nimi','$lyhyt_kuvaus','$kuvaus','$kuva[0]','$kuva[1]','$kuva[2]')") or die (mysql_error());
$tid = mysql_insert_id();
$update = mysql_query("UPDATE kipina_kalenteri SET $paikka = $tid WHERE id = $kalenteri") or die (mysql_error());
header('location: lisaa_tapahtuma.php?tid='.$kalenteri);
}
}
I hope i get answer soon
Someone added or deleted one of the columns in table kipina_kalenteri or kipina_tapahtuma. Because of such situations it's better to always declare to which columns you want to insert.
So it should be like that:
INSERT INTO table (`column1`, `column2`) VALUES ('values1', 'values2');
It's about your table fields. Please define the table field before you start insert a data:
$result = mysql_query("INSERT INTO kipina_kalenteri (`field1`,`field2`,`field3`) VALUES ('$alkupvm','$loppupvm','$muuta')") or die (mysql_error());
so you can sure if the fields are matched with your data

Categories