This is topic PHP file upload: place file information into database (HELP) in forum Film-Yak at Film-Tech Forum ARCHIVE.
To visit this topic, use this URL:
https://ft-forum.com/ft/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic;f=8;t=005530
Posted by Andrew McCrea (Member # 674) on 07-10-2008, 10:30 PM:
Hey everyone!
I'm hoping there's someone out there that's pretty good with PHP that could help me with this script...
This is my script (the action of a form submit) that uploads a file to my server.
quote:
include('config.php');
//Connect to database
$cxn = mysqli_connect($host, $username, $password, ********) or die ("No connection can be made.");
//Get the parent's ID number from URL.
$fID = $_GET['fID'];
//Get the variables from our modFile form.
$title=$_POST['title'];
$desc=$_POST['desc'];
$fGenre=$_POST['fGenre'];
//Get the user's name for proper credit.
$userName=$_SESSION['name'];
// Get the file name and add "m" for MOD file.
$file_name = $_FILES['modFile']['name'];
$uploadLetter=m;
// Random 7 digit number to add to our file name
$random_digit=rand(0000000000,9999999999);
//Here's how we create the new file name.
$new_file_name=$uploadLetter.$random_digit.$file_name;
//set where you want to store files
$path= "files/fileUploads/mods/".$new_file_name;
if($modFile !=none)
{
if(move_uploaded_file($_FILES['modFile']['tmp_name'], $path))
{
echo "Successful<BR/>";
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$_FILES['modFile']['size']."<BR/>";
echo "File Type :".$_FILES['modFile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
mysqli_query($cxn, "INSERT INTO fileAlt (parent, fileName, desc, fileGenre, uploader, filePath) VALUES ('$fID', '$title', '$desc', '$fGenre', '$userName', '$path')") or die ('FAILED.');
The files upload properly, but no information is stored in the database, and I get the die error 'FAILED'.
Could anyone help me correct this script? I'm sure the solution is fairly obvious, but I'm still learning and have tried so many INSERT statement configurations that haven't worked.
Thanks!
Posted by Mark J. Marshall (Member # 1409) on 07-10-2008, 10:51 PM:
To get a clue about why a MySQL query is failing, try using this:
die(mysql_error());
The only problem is that you don't want to leave that there because hackers can gain info about your database from the errors. But in cases like this, you can use this to see what MySQL is complaining about.
The other thing you can try is instead of doing this:
mysqli_query($cxn, "INSERT INTO fileAlt (parent, fileName, desc, fileGenre, uploader, filePath) VALUES ('$fID', '$title', '$desc', '$fGenre', '$userName', '$path')")
...do this:
$query = "INSERT INTO fileAlt (parent, fileName, desc, fileGenre, uploader, filePath) VALUES ('$fID', '$title', '$desc', '$fGenre', '$userName', '$path')";
echo($query);
mysqli_query($cxn, $query);
Then you can actually see what PHP is doing to create your query. And if you like, you can copy and paste that query into something like phpMyAdmin manually to see what happens. Again, this is only for debugging purposes. Once you work it out, get rid of the echo() statement.
Sometimes a name like "O'Malley" will screw up your query because of the single quote. If you're running a whole bunch of names, you might not think of something like that at first.
If that doesn't help, let me know what happens and we'll see what else I can think of.
Posted by Andrew McCrea (Member # 674) on 07-10-2008, 11:05 PM:
I tried the error thing, and received no error output. I then tried mysqli_error and got a "parameter expected 1, null given" type of warning.
Interesting... Here's all the echo output:
quote:
Successful
File Name :m669703611Triple-star_sunset.jpg
File Size :46390
File Type :image/jpeg
INSERT INTO fileAlt (parent, fileName, desc, fileGenre, uploader, filePath) VALUES ('1', 'test', 'test', 'test', '', 'files/fileUploads/mods/m669703611Triple-star_sunset.jpg')
Also, I tried running the insert query in phpMyAdmin and I got this:
quote:
Error
SQL query:
INSERT INTO fileAlt( parent, fileName, DESC , fileGenre, uploader, filePath )
VALUES (
'1', 'test', 'test', 'test', '', 'files/fileUploads/mods/m669703611Triple-star_sunset.jpg'
)
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 'desc, fileGenre, uploader, filePath) VALUES ('1', 'test', 'test', 'test', '', 'f' at line 1
EDIT: The problem turned out to be that 'DESC' is an obscure keyword in PHP or MySQL, so its all fixed now!
Thanks a billion for the tip because it got me thinking creatively again!
Posted by Mark J. Marshall (Member # 1409) on 07-11-2008, 10:22 AM:
Oh yeah, how bout that. DESC is a keyword for ordering things in descending order instead of ascending order. Sorry I missed that!
But those are the things that you sometimes don't think about because you're focused on the one little thing you have in front of you. So, keep that pasting into phpMyAdmin trick handy. It's helpful, especially when verifying queries created dynamically.
Something else you should think about is validating $_POST and $_GET variables before using them directly in a MySQL query. For example, if $_GET['fID'] is supposed to be a number, make sure that it is before using it.
And all variables should be passed through the mysql_escape_string() function. This will automatically escape any single or double quotes or anything else that appears in your string that may otherwise cause MySQL to misbehave. It basically makes any string "MySQL Safe". My suggestion is instead of doing this:
$title=$_POST['title'];
$desc=$_POST['desc'];
$fGenre=$_POST['fGenre'];
Do this:
$mysql['title'] = mysql_escape_string($_POST['title']);
$mysql['desc'] = mysql_escape_string($_POST['desc']);
$mysql['fGenre'] = mysql_escape_string($_POST['fGenre']);
That will make it obvious when you get to your query because you're only using variables from the $mysql[] array.
Those are just my suggestions. Hopefully they're helpful!
Posted by Andrew McCrea (Member # 674) on 07-11-2008, 04:55 PM:
Is that simple cut and past?
Like I said, I'm still very new to PHP, but learning quite quickly, and one problem I've been having is that when someone submits a shout out it dies when a ' is used, but I haven't tried ".
Posted by Mark J. Marshall (Member # 1409) on 07-11-2008, 07:43 PM:
I'm not sure what you mean by simple cut and paste, but yes, the mysql_escape_string() function should fix single quotes and double quotes in your strings.
Feel free to shoot me some questions anytime and I'll be happy to try to help.
Posted by Justin Hamaker (Member # 2165) on 07-14-2008, 05:07 PM:
I would also recommend using stripslashes when retrieving information so that O'Mally doesn't display as O\'Mally. I always include this when retrieving any text field from my database - or before displaying any text field that has been processed by PHP.
The format would usually be:
$text = stripslashes($row['text']); or
$text = stripslashes($text);
Posted by Mark J. Marshall (Member # 1409) on 07-14-2008, 05:44 PM:
O'Mally shouldn't display as O\'Mally when retrieved from the database unless it's stored that way in the database.
You may run into the same problem though if you're trying to pull the name O'Mally out and then use it in something like a php generated javascript routine. For example:
$row['Name'] = "O'Mally"
echo("alert('Hello, ". $row['Name'] .".');");
...would generate a javascript error because it would create:
alert('Hello, O'Mally.');
Posted by Andrew McCrea (Member # 674) on 07-24-2008, 02:42 AM:
OK, so here's something I really need help on, and I don't think its anything major, I just can't sort through everything on Google to really understand what it is I have to do...
I'm building the profile for the users on my site, and I want to show the user's friends a la facebook, with a table like this:

Now, I know how to display images dynamically (like the person's avatar when profile.php is set to show theirs, etc.
What I don't know is how to fetch 6 random rows from the friends table where they're a fan of the user, and display them in the table where I specify...
i.e.
$row[1]['avatar'] $row[1]['name']
$row[2]['avatar'] $row[2]['name']
etc.
I'm sure there's a simple way to do this, I just haven't been able to understand it enough yet to really get it with all my trying...
I appreciate any help I can get!
Posted by Mark J. Marshall (Member # 1409) on 07-24-2008, 06:32 AM:
I'd need a little more info to give an exact answer to the image display question. Specifically, how the names of the avatar files are stored in the database.
In our database, we store the files on the server simply as the number (key id) of the row of the person in the database. For example, if my record in the person table is:
id = 1
name = Mark
Then my picture is stored on the server in an image directory as a file named "1". You could add the extension on that so the file is called "1.jpg" or "1.png" or whatever. But let's assume you have something like this:
id = 1
name = Mark
avatar = avatar1.jpg
And you have 500 people in the table. You want to grab six random people and display their avatars. The query would be something like this:
SELECT * FROM person WHERE <whatever you need here> ORDER BY RAND() LIMIT 6
From there, you make your table. When it comes time to display the avatar, you need something like this:
<img src="/path/to/avatar/directory/<? php echo $row['avatar']; ? >">
(Remove the spaces on the php tags) Does that help?
I notice you're also trying to do three columns and two rows. It occurs to me that maybe that is another part you're having trouble with. When setting that up, you should try to make your code flexible enough so that in the future when you want to change the number of columns from 3 to 4, all you have to do is change one line of code:
$numColumns = 3;
would change to
$numColumns = 4;
I can help you with that too if you need it.
Posted by Andrew McCrea (Member # 674) on 07-24-2008, 10:35 AM:
Yes, I know how to do the grab 6 random and place the echo tag in the image... I've got all of that working on the site so far...
My table looks like this:
profileFriends (table name)
id, person, friend, fAvatar
When someone adds someone as a friend, the user of the site is placed in "person", the friend's name is placed in "friend", and the friend's avatar path is placed in fAvatar (this is updated by the avatar upload script when the avatar is changed).
So, what I'm really looking to do is build an html table, and then pop the image tags and the link tags for the name in each column and each row, so that it displays 6 random friends in this format.
Posted by Andrew McCrea (Member # 674) on 07-25-2008, 12:12 AM:
bump
Posted by Mark J. Marshall (Member # 1409) on 07-25-2008, 11:15 AM:
Looking back at the image you displayed, it looks like you want two rows. One for the avatar, and a second with the name under it. That makes sense if the avatars could be all different sizes. So something like this? (Refresh the page and the names will change. Ignore the broken avatar images - didn't have time to find images of everybody.)
Click Here
Posted by Andrew McCrea (Member # 674) on 07-25-2008, 12:01 PM:
Yes, that looks exactly it.
Posted by Mark J. Marshall (Member # 1409) on 07-25-2008, 12:36 PM:
Ok, I just sent over the code for that via email. Actually it's two emails. The first one had a couple of typos in the code, but I fixed them in the second one. Let me know if you have any questions about anything in there.
Posted by Andrew McCrea (Member # 674) on 07-25-2008, 12:43 PM:
Wow! Thank-you so much! I just got it and can't wait to play with it.
You're a life saver!
Posted by Mark J. Marshall (Member # 1409) on 07-25-2008, 12:59 PM:
My pleasure! Have fun!
Posted by Andrew McCrea (Member # 674) on 07-27-2008, 12:32 AM:
OK, one more quick question:
I'm using that script as an include_once at one part in the script... I want to use several that are customized a bit for different profile items...
How can I use that script several times, because if I have the others included, it throws off the main one you provided...
Posted by Mark J. Marshall (Member # 1409) on 07-27-2008, 08:22 AM:
First, I'm in Houston today, and I may not get to respond again until tomorrow evening.
But I need some more info. Are you saying for example that you modified the script into multiple include files that all do slightly different things but you can't include all of them on the same page for some reason? If that's the case, what happens when you do?
Posted by Andrew McCrea (Member # 674) on 07-27-2008, 10:53 AM:
EDIT: Oops, I read your post wrong...
No, I used the one script several times, slightly modified. It wasn't working, but I changed all the variables and it does now!
I'll make sure to post the link here once the site is up and going (08/08/08).
[ 07-27-2008, 12:51 PM: Message edited by: Andrew McCrea ]
Posted by Mark J. Marshall (Member # 1409) on 07-28-2008, 08:49 AM:
Ah, great! Was there a variable conflict with something else on the page or something?
Posted by Scott Jentsch (Member # 1681) on 07-28-2008, 02:58 PM:
quote: Andrew McCrea
My table looks like this:
profileFriends (table name)
id, person, friend, fAvatar
When someone adds someone as a friend, the user of the site is placed in "person", the friend's name is placed in "friend", and the friend's avatar path is placed in fAvatar (this is updated by the avatar upload script when the avatar is changed).
There may be a reason why you didn't do so, but it would make more sense to have all the users of your site in a table, and then use a cross-reference table that connected all the friends together.
That would keep the avatar referenced only in the users table, and it would not to be repeated in the friends xref table. Duplication is a no-no in databases and should be avoided whenever possible. It's allowable, but not good design, and it will come back to bite you somewhere down the road (usually when you least expect it).
Posted by Andrew McCrea (Member # 674) on 07-29-2008, 08:17 PM:
I'm not that good in PHP, yet! I'm still learning, but I kind of get what you mean.
Posted by Scott Jentsch (Member # 1681) on 07-30-2008, 11:03 AM:
I'll try to illustrate the issue, which is database architecture (not PHP):
Table: users
id
name
avatar
Table: users_xref
user1_id
user2_id
So, take an example where you have three users:
1 - John Smith
2 - Jane Doe
3 - Tom Jones
Tom Jones decides to make Jane Doe and John Smith his friends, so in the users_xref table, you have a record with the following:
user1_id: 3
user2_id: 2
user1_id: 3
user2_id: 1
Now, to find all of Tom Jones' friends, you do a SQL SELECT:
SELECT users.* FROM users, users_xref WHERE users.id = users_xref.user2_id AND users_xref.user1_id = 3
This will result in you getting a list of Tom Jones' friends, their names, and their avatars that you can use to build the listing that you are trying to do.
You will obviously want to build your indexes properly so that you can optimize your queries, and tweak the queries to return the random and/or limited results you are looking for, but the gist of this is that you don't want the avatar reference in multiple tables.
Normalize data whenever possible, and it will keep your databases cleaner and prevent you from pulling your hair out when the inevitable consequences of poor design rear their ugly heads.
Good luck!
Posted by Andrew McCrea (Member # 674) on 07-30-2008, 11:50 AM:
Thank-you very much!
I'm definitely going to start tweaking it. The site is pretty much done now, but I don't see there being an entirely big problem with a tweak like this.
Posted by Andrew McCrea (Member # 674) on 08-08-2008, 10:37 AM:
For anyone interested, my site launched at 8:00am CST.
It is a website where musicians can collaborate with each other online.
Its a tiny bit buggy, a little slow (because its being hosted on an old Windows 2000 running IBM NetVista-- FOR THE TIME BEING), but it works for the most part!
thrusong
Posted by Mark J. Marshall (Member # 1409) on 08-08-2008, 03:29 PM:
Congrats on launching your site! And Scott makes some very good points, although it could be a little better still...
quote: Scott Jentsch
Table: users
id
name
avatar
Table: users_xref
user1_id
user2_id
So, take an example where you have three users:
1 - John Smith
2 - Jane Doe
3 - Tom Jones
Tom Jones decides to make Jane Doe and John Smith his friends, so in the users_xref table, you have a record with the following:
user1_id: 3
user2_id: 2
user1_id: 3
user2_id: 1
Assuming that when Tom adds Jane and John as friends that John & Jane also want Tom as a friend, and assuming that you don't want to duplicate records by also adding:
user1_id: 2
user2_id: 3
user1_id: 1
user2_id: 3
...the query would be:
SELECT
IF(U1.id = '3', U2.name, U1.name) Name,
IF(U1.id = '3', U2.avatar, U1.avatar) Avatar
FROM
users U1 LEFT JOIN
users_xref X ON U1.id = X.user1_id LEFT JOIN
users U2 ON X.user2_id = U2.id
WHERE
X.user1_id = '3' OR X.user2_id = '3'
ORDER BY RAND()
LIMIT 6
Note the four bold threes in that statement. When creating this query in PHP, those are where you will stick the ID of the person you're looking at in order to pull out six random friends of his. To do this though, you should add a two field primary index on the xref table for the user1_id and user2_id fields to avoid duplicates.
If on the other hand, you want your friend relationships to only work one way, then Scott's example is probably fine.
To make it even more like myspace, you could add a field to the xref table called "approved" as an enum 'y', 'n', 'p' (pending), and have the user1_id always be the person making the request. Then you could also query on friends that are awaiting approval from the other person, and people who are requesting to be the user's friend. But maybe I'm getting ahead of myself.
Cheers!
Posted by Andrew McCrea (Member # 674) on 08-08-2008, 11:05 PM:
The site works very much like a typical forum like this, facebook, and YouTube all mixed together...
People can start bands, start albums, start songs, and everyone can offer input all to create a finished song track... Its like "open-sourcing" the music industry since they keep churning out garbage that they charge for. This says "Hey, make better music by offering your input here, giving input there, and hey, maybe get some exposure while you're at it".
That's the basic gist of it, but its so subjective that its hard to define. My financial consultant (who also happens to play the axe for my recording band, ie. we don't do shows, that has used a very minimal, skimmed down thrusong, ie. a file listing directory, and the postal system to work for us) thinks this is a million dollar idea after he saw it at launch today, and I think I'll hit him up for an investment in a good/decent server. I want to look into memcached, in particular, and all sorts of open source technologies. I just know that I want to host it myself, and a lot of that is fed by wanting to learn everything I can (I set up the server by myself, I built the entire site from scratch, with help from amazing people like Mark and Scott on some of the PHP stuff that is explained poorly on the internet).
Right now you can just decide to join a song, band or album, or become a fan of a band or artist (a user of the site), so there's no confirmation needed yet, but eventually, that will definitely be needed.
So, its still a little buggy, but most baby software is, and I have lots of little ideas on how to improve the site. My next big thing is turning everything into components (especially so that the transition to making it available in multiple languages is easier), and adding AJAX.
And one major mission of the site's engineering: Make it about the content, not the site... That's one major problem with the new facebook; It feels like it wants it to be more about the brand then what everyone is up to because its too flashy, in a way.
Posted by Andrew McCrea (Member # 674) on 08-14-2008, 12:50 AM:
So far, so good.
I've started componentizing the site so that all pages are grouped in folders according to "bands", "profile", "home", etc. I think this will keep it more organized and more powerful.
All text is also now filled in as includes according to the selected language. We only have English (Canadian) right now, with English (US) and French to come soon.
Here's a general inquiry.
I'm trying to plan ahead for future expansion, etc. and was wondering how I would handle having several servers and databases.
Like, how could I have two servers, a database on one, and keep track of where files are located in the database?
How does facebook keep track of 10,000+ servers, multiple databases, etc. and keep the site running smoothly? They have something like 1800 MySQL databases...
I'm thinking what I have to start working on is being able to sync two servers so that load balancing can be used to an extent. I also want to have several partitions on each drive and several drives per server , then determine which partition has enough room, keep track of where that file is, etc.
Is there any easy way to get up and going with two servers?
Posted by Mark J. Marshall (Member # 1409) on 08-14-2008, 11:14 AM:
If you want to make the move to multiple servers for expandability sake, the first thing I would do is separate Apache and MySQL onto two separate boxes. Those two programs are performing different functions, and it will be helpful to have them separated out later. Consider that down the road you may have response time problems with MySQL, but Apache may be keeping up with the users just fine... then you can expand your MySQL server farm if need be without touching Apache. Also if your site will have music streaming as part of its functionality, you should split that off as its own server/farm as well for the same reasons. You might find that Apache and MySQL run just fine, but your streaming server is getting clobbered. Then you can deal with that without messing with the other two. That's my suggestion, for what it's worth.
However, if you get one good beefy server it should be able to handle Apache and MySQL just fine for a while, and may even be able to do some streaming too without too much difficulty.
A better bet might be to look at a hosting service. It's worth the money to pay someone else to worry about the hardware! Believe me, the bigger you get, the more important uptime becomes. And the more important uptime becomes, the more time and money you end up spending on infrastructure (A/C, UPS, etc.).
Just a thought.
Posted by Scott Jentsch (Member # 1681) on 08-18-2008, 12:16 PM:
I agree with Mark's comments.
A good hosting provider is a definite plus, as they will do a lot of the heavy lifting for you when it comes to the servers. You will pay for it, but what you get in return is a hosting service that will do what you need it to do.
Even if you go with a single server right now, make sure that your database calls are easy to redirect to a new server when the time comes. Your connections should be in one place, not many, so changing or distributing your calls will not be difficult later on.
Database replication is the name of the game of which you speak, and unless you are tremendously successful with your site (many millions of page views per week), you will not need replication on a well-equipped web server from a company like RackSpace or the like.
Do as much reading as you can about good database design and secure programming. This will pay dividends in the future, trust me! Trust no incoming data, either as a result of form submissions or parameters for your scripts. All incoming data should be guilty until proven innocent and never let the user see the structure of your databases or files, even in error messages (this is easier said than done, but if you get in the habit early, you won't have to go back and fix things to tighten them up later).
When it comes to load issues, the best thing you can do is to create file caches for the data that doesn't change very often. A file call is faster than a complex database call, so don't hit your database any more often than you need to. If the data for a particular band doesn't change until you change it, then destroy and re-create the file cache whenever that information changes.
An efficient caching scheme will buy you lots of horsepower on the server side of things, and you will get much more out of much less hardware. Simultaneous MySQL sessions will most likely limit you before the number of simultaneous Apache sessions.
Posted by Andrew McCrea (Member # 674) on 08-30-2008, 04:08 PM:
Thanks for all the helpful information, I'm definitely taking it to heart in the site's evolution.
Here's a question with probably a 2-second solution: When people are entering their profile information, song lyrics, etc., in a text box, it stores correctly, but I can't get it to format the same way in the HTML output when its retrieved...
I've tried <pre> which stretches out the HTML tables and breaks the pages by keeping everything on one line.
When I retrieve it into a text box to display on an edit page, the line breaks and formatting are all there, so its in the database right... I just want it to continue the sentence on a new line instead of stretching the HTML table.
Posted by Mark J. Marshall (Member # 1409) on 08-30-2008, 06:31 PM:
Does this work?
echo(nl2br($text));
Posted by Andrew McCrea (Member # 674) on 09-01-2008, 01:56 PM:
That works pretty well, thanks!
I start school tomorrow and we learn ASP.net this year... Were you self taught in PHP or did you take formal learning?
Posted by Mark J. Marshall (Member # 1409) on 09-01-2008, 09:58 PM:
I'm pretty much self taught. I started programming at about age 11 on a TI-99/4a in TI BASIC. At about age 12 we upgraded to Extended BASIC. I also fiddled around with various Apple IIs in middle and high school. Eventually around the end of high school I ended up with an Amiga 500 and started programming in Amiga BASIC.
I read books on Pascal and C late in high school, but was never able to actually use them until college when I took an Introduction to C class and got to play with a C compiler. That was about the extent of my formal programming training. PHP is structured a lot like C, so it was easy for me to pick it up and run with it. I've never used asp.net, so I don't know much about it, but I know it serves just about the same purpose as PHP.
Good luck in your class!
Posted by Andrew McCrea (Member # 674) on 09-06-2008, 05:49 PM:
I really appreciate all the help and stories.
I have a question (I'm not looking for code, just a description): What kind of approach would I take to do a news feed like Facebook, where it pulls up the most recent activities of my users' favourite artists (i.e. friend) on the site?
Powered by Infopop Corporation
UBB.classicTM
6.3.1.2