Jump to content

Upload image code trying to add db connect to it


Html

Recommended Posts

Hi,

I want to get this code to have some connection with a db,

I tried to get these in the db, but it won't create, I used it from a sql example.

CREATE TABLE IF NOT EXISTS images (
id id UNSIGNED NOT NULL AUTO_INCREMENT
img VARCHAR(20) NOT NULL,
)

INSERT INTO images
( id, images,)
VALUES
( "id","images/")

I want to store an uploaded image, so an id and where it would be stored. Since the code has been setup a particular way with what I am using, I'll need to add some bits from the other.

 

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP File Upload</title>
</head>
<body>
<form method="POST" action="<?php $_SERVER[ 'PHP_SELF' ] ?>" enctype="multipart/form-data">
Select an image to upload :
<input type="file" name="image" >
<input type="submit" value="Upload Image" >
</form>   
<?php
  # Open database connection.
require ( 'connect_db.php' ) ;
  
# DISPLAY COMPLETE LOGGED IN PAGE.

# Access session.
session_start() ; 

# Redirect if not logged in.
if ( !isset( $_SESSION[ 'user_id' ] ) ) { require ( 'login_tools.php' ) ; load()
  
  # Retrieve selective item data from 'images' database table. 
$q = "SELECT * FROM umages WHERE id = $id" ;
$r = mysqli_query( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
  $row = mysqli_fetch_array( $r, MYSQLI_ASSOC );
  
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )
{
  $name = $_FILES[ 'image' ][ 'name' ] ;
  $temp = $_FILES[ 'image' ][ 'tmp_name' ] ;
  $size = $_FILES[ 'image' ][ 'size' ] ;
  $ext = pathinfo( $name , PATHINFO_EXTENSION ) ;
  $ext = strtolower( $ext ) ;
  if( $ext != 'png' && $ext != 'jpg' && $ext != 'gif' )
  { echo 'Format must be PNG, JPG, or GIF' ; exit() ; }  
  if( $size > 512000)
  { echo 'File size must not exceed 500Kb' ; exit() ; }
  if( file_exists( $name ) )
  { echo 'File '.$name.' already uploaded' ; exit() ; }
  try
  {
    move_uploaded_file( $temp , $name ) ;
    echo 'File uploaded : '.$name ;
    echo '<br><img src="'.$name.'">' ;
  }
  catch( Exception $e )
  { echo 'File upload failed!' ; }
} 
?> 
</body>
</html>
<?php # DISPLAY COMPLETE LOGGED IN PAGE.

# Access session.
session_start() ; 

# Redirect if not logged in.
if ( !isset( $_SESSION[ 'user_id' ] ) ) { require ( 'login_tools.php' ) ; load()

I've added in the following, since all the files tend to have that common pieces of php, I am guessing this is the way it works. Tried in the past using what ever, and didn't work.

I got this bit of code from added.php which is a file linked with a shop/cart system, I never viewed those example files, since I didn't need them or want to know what they were, I was only trying to use what I want and add to it, I've realised that the whole example files are structured a certain way and there isn't much bending to only break them, and they don't even work if they are backups to load into a new account. So its really try them and be stuck with them, and hope the free host doesn't vanish anytime soon.

# Get passed product id and assign it to a variable.
if ( isset( $_GET['id'] ) ) $id = $_GET['id'] ;

That there is what I'd need for a profile index page. I looked further into the example files and found a actual id, name, and forum, while it wasn't any different than the Php 7 book I have from the small company that sold it, the other does contain at least what I wanted, just lacks an actual individual profile to view linked comments to a logged in user.

Edited by Html
Link to comment
Share on other sites

  • Replies 80
  • Created
  • Last Reply

Top Posters In This Topic

After move_uploaded_file just do simple sql query that adds the information to database. You already have all the available information ready. If you only have 2 columns on database, you only need the image name stored, since id is auto_integer primary key (so its auto generated).

What kind of issues are you having with your code?

More about file upload: https://www.w3schools.com/php/php_file_upload.asp
More about sql insert: https://www.w3schools.com/php/php_mysql_insert.asp

 

 

Link to comment
Share on other sites

The upload is simply from a example file on how to upload a file, but I want to obviously store an uploaded image in a db, which is linked with a particular user who is logged in, so I am just guessing the above should work with these added code snippets taken from a core file. The image upload code works completely fine as is, I tried this in the past, but I didn't know what to do, so I've posted what I think is perhaps the way to get this working.

As for the problem currently getting the table created by using the sql example, I just edited to two columns, id, and image

CREATE TABLE IF NOT EXISTS images (
id id UNSIGNED NOT NULL AUTO_INCREMENT
img VARCHAR(20) NOT NULL,
)

INSERT INTO images
( id, images,)
VALUES
( "id","images/")

Something about the top just won't create. Even if I include ; after the bracket.

As for insert, you are referring to this part?

# Retrieve selective item data from 'images' database table. 
$q = "INSERT * INTO images WHERE (id, images,)VALUES ('id','images');
$r = mysqli_query( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
  $row = mysqli_fetch_array( $r, MYSQLI_ASSOC );

 

Edited by Html
Link to comment
Share on other sites

I see 3 syntax errors in your code that will stop anything from running, and 2 runtime errors that will cause problems if you actually get it to run.  To start with, count the opening and closing brackets.  Those should be the same number.

Quote

Something about the top just won't create. Even if I include ; after the bracket.

Yeah, you've got several syntax errors in that too.  You've got commas where they shouldn't be, and missing commas where they should be.

 

Quote

As for insert, you are referring to this part?

 

Even that has syntax errors.  You've got an opening double quote, where's the double quote to close the string?  And the SQL query in your PHP has 2 syntax errors. There's only 9 words in it.

You really need to pay attention to this stuff.  Syntax errors stop any code from running.  And yes, adding just a single syntax error in a piece of code because you aren't paying attention means that now nothing works.

Link to comment
Share on other sites

As for SQL try this

CREATE TABLE IF NOT EXISTS images (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
img VARCHAR(20) NOT NULL
)
INSERT INTO images
(img)
VALUES
("imageurl")

 

Link to comment
Share on other sites

9 minutes ago, Mudsaf said:

As for SQL try this


CREATE TABLE IF NOT EXISTS images (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
img VARCHAR(20) NOT NULL
)

INSERT INTO images
(img)
VALUES
("imageurl")

 

Why imageurl? I got the idea from the /images/file.png table of the cart.

 

12 minutes ago, justsomeguy said:

I see 3 syntax errors in your code that will stop anything from running, and 2 runtime errors that will cause problems if you actually get it to run.  To start with, count the opening and closing brackets.  Those should be the same number.

Yeah, you've got several syntax errors in that too.  You've got commas where they shouldn't be, and missing commas where they should be.

 

 

Even that has syntax errors.  You've got an opening double quote, where's the double quote to close the string?  And the SQL query in your PHP has 2 syntax errors. There's only 9 words in it.

You really need to pay attention to this stuff.  Syntax errors stop any code from running.  And yes, adding just a single syntax error in a piece of code because you aren't paying attention means that now nothing works.

Hmm, I haven't tried it, but I was thinking I doubt this would work right off what I just thought up. The cart.php file gave me the thought.

There are six of these { on the outer part of the code.

Edited by Html
Link to comment
Share on other sites

Just now, Html said:

Why imageurl? I got the idea from the /images/file.png table of the cart.

  

Hmm, I haven't tried it, but I was thinking I doubt this would work right off what I just thought up. The cart.php file gave me the thought.

It was just example text that you could insert to the database. (Whatever you want to insert into img column, usually the filepath+name as you mentioned)

Link to comment
Share on other sites

I tried this,

CREATE TABLE IF NOT EXISTS images (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
img VARCHAR(20) NOT NULL
)
INSERT INTO images
(img)
VALUES
("images")

#1064 - 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 'INSERT INTO images (img) VALUES ("images")' at line 5
 
VALUES ( "Rhino", "A friendly jungle buddy.", "images/rhino.png",29.99 );
 
This is the example from the sql file.
Link to comment
Share on other sites

CREATE TABLE IF NOT EXISTS images (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
img VARCHAR(20) NOT NULL
PRIMARY KEY (item_id)
);
INSERT INTO images
(img)
VALUES
("images")

Error

SQL query:

CREATE TABLE IF NOT EXISTS images(

id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
img VARCHAR( 20 ) NOT NULL PRIMARY KEY ( item_id )

);
 

 

MySQL said: Documentation

#1064 - 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 '(item_id)
)' at line 4

 

I guess id alone won't work for creating a new table?

Link to comment
Share on other sites

22 minutes ago, Html said:
VALUES ( "Rhino", "A friendly jungle buddy.", "images/rhino.png",29.99 );
 

What you are trying to do isn't going to work with the table you just created. You need to make 3 more columns to your database table to be able to fill the rest of information in your query.

Example scenario account information

id int auto_increment primary key | username varchar(50) | password varchar(128) | email (varchar150) unique

So lets pretend that the table we created with the "create table" query. So we wound have to do insert query like below.

insert into accounts (username,password,email) values (value1,value2,value3)

 

Edited by Mudsaf
Link to comment
Share on other sites

14 hours ago, Mudsaf said:

What you are trying to do isn't going to work with the table you just created. You need to make 3 more columns to your database table to be able to fill the rest of information in your query.

Example scenario account information

id int auto_increment primary key | username varchar(50) | password varchar(128) | email (varchar150) unique

So lets pretend that the table we created with the "create table" query. So we wound have to do insert query like below.


insert into accounts (username,password,email) values (value1,value2,value3)

 

The whole point was just show where I got the whole view from. So id and images is what I need, so three, so what is the third one?

 

3 hours ago, dsonesuk said:

Could you please stick with single SQL statement to get that to work, instead of introducing every sql statement you find on the internet, you'll never reach your goal if you continuously move the goal posts.

I just got this idea from the other day while viewing the files, so I'm all over the place with this.

Link to comment
Share on other sites

18 hours ago, Html said:

MySQL said: Documentation

#1064 - 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 '(item_id)
 )' at line 4

Check the item_id where you are getting the error. You are trying to create it as primary key, but you only have column called id. As justsomeguy told you have to pay attention to details.

 

18 hours ago, Html said:

CREATE TABLE IF NOT EXISTS images (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
img VARCHAR(20) NOT NULL
PRIMARY KEY (item_id)
);
INSERT INTO images
(img)
VALUES
("images")

Check the underlined areas, also you are missing a comma before primary key. Below working example.

CREATE TABLE IF NOT EXISTS images (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
img VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);

INSERT INTO images (img) VALUES ("testx");

 

Link to comment
Share on other sites

21 hours ago, justsomeguy said:

I see 3 syntax errors in your code that will stop anything from running, and 2 runtime errors that will cause problems if you actually get it to run.  To start with, count the opening and closing brackets.  Those should be the same number.

Yeah, you've got several syntax errors in that too.  You've got commas where they shouldn't be, and missing commas where they should be.

 

 

Even that has syntax errors.  You've got an opening double quote, where's the double quote to close the string?  And the SQL query in your PHP has 2 syntax errors. There's only 9 words in it.

You really need to pay attention to this stuff.  Syntax errors stop any code from running.  And yes, adding just a single syntax error in a piece of code because you aren't paying attention means that now nothing works.

I decided to do a check on the code. It now states the only error so far is $q, of course this is used in the code numerous times from the example files, I imagine it is key to getting anything done with any of the files.

Link to comment
Share on other sites

<?php
  # Open database connection.
require ( 'connect_db.php' ) ;
  
# DISPLAY COMPLETE LOGGED IN PAGE.

# Access session.
session_start() ; 

# Redirect if not logged in.
if ( !isset( $_SESSION[ 'user_id' ] ) ) { require ( 'login_tools.php' ) ; load()
  
  # Retrieve selective item data from 'images' database table. 
$q = "SELECT * FROM umages WHERE id = $id" ;
$r = mysqli_query( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
  $row = mysqli_fetch_array( $r, MYSQLI_ASSOC );
  
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )

  $name = $_FILES[ 'image' ][ 'name' ] ;
  $temp = $_FILES[ 'image' ][ 'tmp_name' ] ;
  $size = $_FILES[ 'image' ][ 'size' ] ;
  $ext = pathinfo( $name , PATHINFO_EXTENSION ) ;
  $ext = strtolower( $ext ) ;
  if( $ext != 'png' && $ext != 'jpg' && $ext != 'gif' )
  { echo 'Format must be PNG, JPG, or GIF' ; exit() ; }  
  if( $size > 512000)
  { echo 'File size must not exceed 500Kb' ; exit() ; }
  if( file_exists( $name ) )
  { echo 'File '.$name.' already uploaded' ; exit() ; }
  try
  
    move_uploaded_file( $temp , $name ) ;
    echo 'File uploaded : '.$name ;
    echo '<br><img src="'.$name.'">' ;
  }
  catch( Exception $e )
  { echo 'File upload failed!' ; }
} 
?> 

This appears to be better, sure the same error for the $q = "SELECT * FROM umages WHERE id = $id" ;

Link to comment
Share on other sites

53 minutes ago, Html said:

Right okay, that has worked, so the example of having an image uploaded, does this mean that it goes within the main folder of the files?

Thank you.

You can store wherever you want as long as you know the path you store them. If you want to store outside of www directory then you need to use php readfile() and store mime_types, but that gets bit more complex.

Edited by Mudsaf
fixed fopen to readfile
Link to comment
Share on other sites

Well I'd like to store them in the directory that is where the files are, may be in images folder, I have one already, it is setup from the example files, that is images/file.jpg is.

Link to comment
Share on other sites

<?php
  # Open database connection.
require ( 'connect_db.php' ) ;
  
# DISPLAY COMPLETE LOGGED IN PAGE.

# Access session.
session_start() ; 

# Redirect if not logged in.
if ( !isset( $_SESSION[ 'user_id' ] ) ) { require ( 'login_tools.php' ) ; load()
  
  # Retrieve selective item data from 'images' database table. 
$q = "SELECT * FROM images WHERE id = $id" ;
$r = mysqli_query( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
  $row = mysqli_fetch_array( $r, MYSQLI_ASSOC );
  
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )

  $name = $_FILES[ 'image' ][ 'name' ] ;
  $temp = $_FILES[ 'image' ][ 'tmp_name' ] ;
  $size = $_FILES[ 'image' ][ 'size' ] ;
  $ext = pathinfo( $name , PATHINFO_EXTENSION ) ;
  $ext = strtolower( $ext ) ;
  if( $ext != 'png' && $ext != 'jpg' && $ext != 'gif' )
  { echo 'Format must be PNG, JPG, or GIF' ; exit() ; }  
  if( $size > 512000)
  { echo 'File size must not exceed 500Kb' ; exit() ; }
  if( file_exists( $name ) )
  { echo 'File '.$name.' already uploaded' ; exit() ; }
  try
  
    move_uploaded_file( $temp , $name ) ;
    echo 'File uploaded : '.$name ;
    echo '<br><img src="'.$name.'">' ;
  }
  catch( Exception $e )
  { echo 'File upload failed!' ; }
} 
?> 


Okay, well nothing displays.

<?php
  # Open database connection.
require ( 'connect_db.php' ) ;
  
# DISPLAY COMPLETE LOGGED IN PAGE.

# Access session.
session_start() ; 

# Redirect if not logged in.
if ( !isset( $_SESSION[ 'user_id' ] ) ) { require ( 'login_tools.php' ) ; load()
  
  # Retrieve selective item data from 'images' database table. 
$q = "SELECT * FROM images WHERE id = $id" ;
$r = mysqli_query( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
  $row = mysqli_fetch_array( $r, MYSQLI_ASSOC );
  
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )

  $name = $_FILES[ 'image' ][ 'name' ] ;
  $temp = $_FILES[ 'image' ][ 'tmp_name' ] ;
  $size = $_FILES[ 'image' ][ 'size' ] ;
  $ext = pathinfo( $name , PATHINFO_EXTENSION ) ;
  $ext = strtolower( $ext ) ;
  if( $ext != 'png' && $ext != 'jpg' && $ext != 'gif' )
  { echo 'Format must be PNG, JPG, or GIF' ; exit() ; }  
  if( $size > 512000)
  { echo 'File size must not exceed 500Kb' ; exit() ; }
  if( file_exists( $name ) )
  { echo 'File '.$name.' already uploaded' ; exit() ; }
  try
  
    move_uploaded_file( $temp , $name ) ;
    echo 'File uploaded : '.$name ;
    echo '<br><img src="'.$name.'">' ;
  }
  catch( Exception $e )
  { echo 'File upload failed!' ; }
  
# Close database connection.
mysqli_close( $dbc ) ;
?> 

I tried removing the top curly brace

if ( mysqli_num_rows( $r ) == 1 )
{
$row = mysqli_fetch_array( $r, MYSQLI_ASSOC );
 

I removed the bottom as the code above displays, no change.

Edited by Html
No change
Link to comment
Share on other sites

Sure, I thought, yeah may be this may work, I don't remember what I didn't do the last time when I tried this. I get you're point.

I think I messed with the files I had, and didn't do certain things with it properly.

I got this setup, it wasn't the first user site I setup, but this is what I did so far, I run out of any credible ideas, I just made this generic. aboringsocialnetworksite.epizy.com

I'm going to tinker with what I can, I loaded in duplicated files that were not edited, and they work, when i tried with the old files I had, I don't think I have a backup, but it was inferior in functions compared to this as the whole files. I was trying to do my own stuff with it, but it wouldn't work, the code is dated, and structured a certain way with $q as one user on here helped me with this months ago.

But anyway, I probably made errors with the first files that caused them to stop working when I loaded them as a backup.

 

 

Edited by Html
Link to comment
Share on other sites

But! If you don't understand what it does, why its done this way, you will go round and round in cycles, probably none of it will work because it not done in correct order. For instance, you should know that session_start() should be placed at the top of page before ANYTHING  I mean ANYTHING else! that is the first thing that is highlighted in the tutorial, that is why copy and paste which is what you are doing without understanding the structure on how to use the code is bad and wastes a lot of time for a simple correction of placing single short line of code at top.

Link to comment
Share on other sites

I didn't think about that, since I haven't made any scratch made code. I have only used example code is what I am focusing on now and trying to get something working, it should work out okay, if not well worth a try.

Okay I have corrected that, every page does have that at the top.

As for the any more errors line 15 is the returning one.

<?php

# Access session.
session_start() ; 

  # Open database connection.
require ( 'connect_db.php' ) ;
  
# DISPLAY COMPLETE LOGGED IN PAGE.

# Redirect if not logged in.
if ( !isset( $_SESSION[ 'user_id' ] ) ) { require ( 'login_tools.php' ) ; load()
  
  # Retrieve selective item data from 'images' database table. 
$q = "SELECT * FROM images WHERE id = $id" ;
$r = mysqli_query( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
  $row = mysqli_fetch_array( $r, MYSQLI_ASSOC );
  
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )

  $name = $_FILES[ 'image' ][ 'name' ] ;
  $temp = $_FILES[ 'image' ][ 'tmp_name' ] ;
  $size = $_FILES[ 'image' ][ 'size' ] ;
  $ext = pathinfo( $name , PATHINFO_EXTENSION ) ;
  $ext = strtolower( $ext ) ;
  if( $ext != 'png' && $ext != 'jpg' && $ext != 'gif' )
  { echo 'Format must be PNG, JPG, or GIF' ; exit() ; }  
  if( $size > 512000)
  { echo 'File size must not exceed 500Kb' ; exit() ; }
  if( file_exists( $name ) )
  { echo 'File '.$name.' already uploaded' ; exit() ; }
  try
  
    move_uploaded_file( $temp , $name ) ;
    echo 'File uploaded : '.$name ;
    echo '<br><img src="'.$name.'">' ;
  }
  catch( Exception $e )
   echo 'File upload failed!' ; }
  
# Close database connection.
mysqli_close( $dbc ) ;
?> 

 

Edited by Html
Line #15
Link to comment
Share on other sites

24 minutes ago, Html said:

$q = "SELECT * FROM images WHERE id = $id" ;

Where have you defined variable called $id, for sure I cannot see one in this code.

Edited by Mudsaf
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...