Membership
Main Menu
Forum Boards
Stats
- 20 tutorials
- 74,816 members
- 734,950 forum posts
- 13 blog posts
Tutorials
PHP Basic Database Handling
Views: 67594
Dealing With The Database: INSERT
In this first chunk of code, we will add a new name to the table, if applicable.
02. We first check our post array to see if the user entered a name.
04. If he did, we use mysql_real_escape_string as a measure to prevent sql injection attacks (good idea to read up on how to prevent sql injection attacks, since you're learning how to work with databases now).
06. The next thing we do is make our query string. The string looks just like how you would put it directly into your database, except you have " "'s wrapped around and you're assigning it to a variable.
07. The last thing we do is send the query string to the database. We do this with the mysql_query function. mysql_query only requires one argument: the query string. You don't even have to give it as a variable. You can use the string itself as the argument (wrapped in quotes). I like to keep the string separated from the mysql_query because it's easier to debug if things go wrong.
As with many mysql related functions, mysql_query accepts an optional 2nd argument to specify the connection stream.
You don't technically need to assign mysql_query to a variable. When PHP executes mysql_query, it will either will return a result source if you're expecting some kind of data to be returned, a boolean value "true" (represented by "1") if the query was a success but no data is being returned, or a boolean value "false" (represented by "0") if for some reason the query failed.
Since you will usually always want to know how the query went (like, you're expecting data, or need to know if it failed or not), you need to assign that to a variable. Ideally you will want to setup some kind of error event trapping in case something goes wrong, or check if it's a success so you can tell the user or something, but to keep it simple, I haven't really done anything like that in this script, so I technically didn't need to have that "$result = " part. But it's a habit of mine to do it anyway.
