Jump to content
Vlad232

Intrebare PHP/MYSQL (insert into)

Recommended Posts

Salut, m-am apucat de facut un cloud storage simplu, pentru mine, unde sa-mi tin fisierele, Cand incarc fisierele, eu doresc sa scrie pe fiecare fisier incarcat numele celui care il incarca. Am facut un tabel tbl_uploads si acolo am pus la fiecare si o sectiune userName, pe langa fisierul acela, dimensiunea si tipul lui. Dar, am incercat sa lucrez ceva sa trimita si numele dar nu reusesc. Va las codul mai jos, sper sa ma puteti ajuta. Daca nu sunteti siguri cu ce doresc, mai puteti da reply si eu va raspund.

<?php
//UPLOAD.PHP
include_once 'dbconnect.php';
if(isset($_POST['btn-upload']))
{

 $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
 $file_size = $_FILES['file']['size'];
 $file_type = $_FILES['file']['type'];
 $folder="uploads/";


 $new_size = $file_size/1024;



 $new_file_name = strtolower($file);

 $final_file=str_replace(' ','-',$new_file_name);
//Aici am incercat sa fac sa trimit in baza alaturi de fisier si numele celui care trimite.
 $userName =  mysql_real_escape_string($_SESSION['user']);
 $query = "SELECT * FROM users WHERE userName = '$userName'";
 $result = mysql_query($query);
 $row = mysql_fetch_array($result);
 if(move_uploaded_file($file_loc,$folder.$final_file))
 {


  $sql="INSERT INTO tbl_uploads(userName,file,type,size) VALUES('$row','$final_file','$file_type','$new_size')";
  mysql_query($sql);
  ?>
  <script>
  alert('Incarcat cu succes!');
        window.location.href='home.php?success';
        </script>
  <?php
 }
 else
 {
  ?>

  <?php
 }
}
?>

Aici o sa pun ce am in HTML pentru incarcarea fisierului.

<div id="body">
 <form action="upload.php" method="post" enctype="multipart/form-data">
 <input type="file" name="file" />
 <button type="submit" name="btn-upload">Incarca</button>
 </form>
    <br /><br />
    <?php
 if(isset($_GET['success']))
 {
  ?>
        <label>Fisier uploadat cu succes.</label>
        <?php
 }
 else if(isset($_GET['fail']))
 {
  ?>
        <label>A aparut o problema, iar fisierul nu s-a incarcat!</label>
        <?php
 }
 else
 {
  ?>
        <?php
 }
 ?>

Multumesc!

Edited by Vlad232

Share this post


Link to post
Share on other sites

Din moment ce la:

$sql="INSERT INTO tbl_uploads(userName,file,type,size) VALUES('$row','$final_file','$file_type','$new_size')";

Insertezi tot array-ul $row, adica user-ul complet fiindca mai sus faci:

$query = "SELECT * FROM users WHERE userName = '$userName'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

Inloc de $row la VALUES ar trebuii sa folosesti:

$row['id']

Sau:

$row['userName']

Depinde ce tip este coloana userName de la tabla tbl_uploads. Daca este de tip INT, atunci trebuie sa salvezi ID-ul, daca este string, username-ul.

Ar trebuii sa te uiti peste urmatoarele tutoriale si sa faci niste legaturi intre table.

https://www.w3schools.com/sql/sql_foreignkey.asp

https://www.w3schools.com/sql/sql_join.asp


PHP Developer - Not available for freelancing right now

Daca ai de gand sa postezi la categoria IPB, nu uita sa citesti regulamentul: Link regulament

Share this post


Link to post
Share on other sites
1 hour ago, gadeas said:

Din moment ce la:


$sql="INSERT INTO tbl_uploads(userName,file,type,size) VALUES('$row','$final_file','$file_type','$new_size')";

Insertezi tot array-ul $row, adica user-ul complet fiindca mai sus faci:


$query = "SELECT * FROM users WHERE userName = '$userName'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);

Inloc de $row la VALUES ar trebuii sa folosesti:


$row['id']

Sau:


$row['userName']

Depinde ce tip este coloana userName de la tabla tbl_uploads. Daca este de tip INT, atunci trebuie sa salvezi ID-ul, daca este string, username-ul.

Ar trebuii sa te uiti peste urmatoarele tutoriale si sa faci niste legaturi intre table.

https://www.w3schools.com/sql/sql_foreignkey.asp

https://www.w3schools.com/sql/sql_join.asp

La chestia aia m-am gandit si am si facut-o mai demult, dandu-mi eroarea care o am si acum: 

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\cloudstorage\upload.php on line 30

Linia 30: 

  $sql="INSERT INTO tbl_uploads(userName,file,type,size) VALUES($row['id'],'$final_file','$file_type','$new_size')";

Variabila este de tip Varchar, am incercat sa trimit si cu id si cu userName, o seara faina sa ai, mersi!

Edited by Vlad232

Share this post


Link to post
Share on other sites

$_SESSION['user'] contine ceva?

Poti verifica cu:

var_dump($_SESSION['user']);
exit;

Intre cod PHP.


PHP Developer - Not available for freelancing right now

Daca ai de gand sa postezi la categoria IPB, nu uita sa citesti regulamentul: Link regulament

Share this post


Link to post
Share on other sites
5 minutes ago, gadeas said:

$_SESSION['user'] contine ceva?

Poti verifica cu:


var_dump($_SESSION['user']);
exit;

Intre cod PHP.

Da, iti spune daca esti logat, il folosesc cand verific daca respectivul user este logat pe site. @gadeas

Il mai folosesc si cand afisez la titlu numele respectivului: 

	if( !isset($_SESSION['user']) ) {
		header("Location: index.php");
		exit;
	}

	$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysql_fetch_array($res);
 + html la mijloc: 
<title>Bine ai venit - <?php echo $userRow['userName']; ?></title>

 

Edited by Vlad232

Share this post


Link to post
Share on other sites

Incearca asa:

  $sql="INSERT INTO tbl_uploads(userName,file,type,size) VALUES('{$row['id']}','$final_file','$file_type','$new_size')";

Sau:

  $sql="INSERT INTO tbl_uploads(userName,file,type,size) VALUES('" . $row['id'] . "','$final_file','$file_type','$new_size')";

 


PHP Developer - Not available for freelancing right now

Daca ai de gand sa postezi la categoria IPB, nu uita sa citesti regulamentul: Link regulament

Share this post


Link to post
Share on other sites
22 hours ago, gadeas said:

Incearca asa:


  $sql="INSERT INTO tbl_uploads(userName,file,type,size) VALUES('{$row['id']}','$final_file','$file_type','$new_size')";

Sau:


  $sql="INSERT INTO tbl_uploads(userName,file,type,size) VALUES('" . $row['id'] . "','$final_file','$file_type','$new_size')";

 

Nu a mers, pur si simplu nu mai face nimic functia de upload, nici macar nu imi afiseaza daca a dat eroare sau ceva, pur si simplu ramane pe home.php :(

Share this post


Link to post
Share on other sites

Pune sus de tot dupa include-uri:

error_reporting(E_ALL);

Pentru a vedea orice fel de eroare, daca tot nu apare nimic, verifica logu de la Apache.


PHP Developer - Not available for freelancing right now

Daca ai de gand sa postezi la categoria IPB, nu uita sa citesti regulamentul: Link regulament

Share this post


Link to post
Share on other sites

Apache log: 

[Mon Mar 20 09:39:00.352837 2017] [:error] [pid 3432:tid 1724] [client ::1:50534] PHP Notice:  Undefined variable: _SESSION in C:\\xampp2\\htdocs\\germana\\upload.php on line 27, referer: http://localhost/germana/home.php?success
[Mon Mar 20 09:39:00.352837 2017] [:error] [pid 3432:tid 1724] [client ::1:50534] PHP Warning:  mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\\xampp2\\htdocs\\germana\\upload.php on line 28, referer: http://localhost/germana/home.php?success

 

Share this post


Link to post
Share on other sites

Acolo si problema in aldoilea rand.

$_SESSION nu exista, probabil iti lipseste un session_start(); ?

De aia totu ce este in continuare nu mai merge deloc, fiindca query-ul iti returneaza probabil false. Ar fi ok sa faci verificari de fiecare data cand faci un query sa vezi daca a adus ceva sau nu, nu direct sa crezi ca aduce todeauna, pentru ca vor fi cazuri cand nu va gasi niciun rezultat in baza de date.


PHP Developer - Not available for freelancing right now

Daca ai de gand sa postezi la categoria IPB, nu uita sa citesti regulamentul: Link regulament

Share this post


Link to post
Share on other sites
12 hours ago, gadeas said:

Acolo si problema in aldoilea rand.

$_SESSION nu exista, probabil iti lipseste un session_start(); ?

De aia totu ce este in continuare nu mai merge deloc, fiindca query-ul iti returneaza probabil false. Ar fi ok sa faci verificari de fiecare data cand faci un query sa vezi daca a adus ceva sau nu, nu direct sa crezi ca aduce todeauna, pentru ca vor fi cazuri cand nu va gasi niciun rezultat in baza de date.

Am pus si session_start() si apare aceeasi eroare.

 

Edited by Vlad232

Share this post


Link to post
Share on other sites

Eu zic sa faci o verificare inainte cu var_dumpuri si sa vezi ce-ti returneaza $_SESSION. Fiindca eu tot cred ca returneaza null. Si avand in vedere ca nu faci nici-o verificare in toata pagina daca X parametru e null sau empty, e si normal sa deie eroare si sa nu mearga, fiindca probabil ceva nu e bine.


PHP Developer - Not available for freelancing right now

Daca ai de gand sa postezi la categoria IPB, nu uita sa citesti regulamentul: Link regulament

Share this post


Link to post
Share on other sites
12 hours ago, gadeas said:

Eu zic sa faci o verificare inainte cu var_dumpuri si sa vezi ce-ti returneaza $_SESSION. Fiindca eu tot cred ca returneaza null. Si avand in vedere ca nu faci nici-o verificare in toata pagina daca X parametru e null sau empty, e si normal sa deie eroare si sa nu mearga, fiindca probabil ceva nu e bine.

var_dump($_SESSION['user']);
exit; afiseaza 

string(1) "8"

"8" e id-ul contului cu care sunt logat. Dar daca afisez in var_dump userName in loc de user imi da: 


Notice: Undefined index: userName in C:\xampp2\htdocs\cloudstorage\upload.php on line 6
NULL
Am mai incercat o chestie: 
  $res=mysql_query("SELECT userName FROM users WHERE userId=".$_SESSION['user']);
  $userRow=mysql_fetch_array($res);
error_reporting(E_ALL);
  var_dump($userRow['userName']);
exit;

Si imi afiseaza numele contului

string(4) "test"

Asa ca, am trimis in baza $userRow['userName'] si a functionat, multumesc mult pentru tot ajutorul dat.

CkxIinf.png?1

 

Edited by Vlad232

Share this post


Link to post
Share on other sites

Incearca acest cod:

<?php
session_start();
//UPLOAD.PHP
//include'dbconnect.php';
$db = new mysqli('localhost', 'root', '', 'test') or die('Error the connection to database!');

if(isset($_POST['btn-upload'])) {
    $fileName = rand(1000,100000)."-".$_FILES['file']['name'];

    if ($_FILES["file"]["size"] > 1024) {
        if ($_FILES["file"]["error"] > 0) {
                    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        } else {
            echo "Upload: " . $_FILES["file"]["name"] . "<br />";
            echo "Type: " . $_FILES["file"]["type"] . "<br />";
            echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
            echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

            if (file_exists("/uploads/" . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists. ";
            } else if (move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $fileName)) {
                $userName = $_SESSION['userName'];
                $file = $fileName;
                $file_type = $_FILES["file"]["type"];
                $file_size = $_FILES["file"]["size"];

                $sql = "INSERT INTO tbl_uploads (userName, file, type, size) VALUES ('$userName','$file','$file_type','$file_size')";
                mysqli_query($db, $sql);
                echo "Stored in: " . "/uploads/" . $fileName;
            }
        }
    } else {
        echo "Fisier invalid!";
    }
}
?>

<div id="body">
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <button type="submit" name="btn-upload">Incarca</button>
    </form>
</div>

Acum este imposibil sa iti mai dea erori (incarca poze/fisiere si introduce si in baza de date detaliile pozei/fisierului)

Edited by Jetix
  • Sad 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...