EDIT: 03/01/2009
NOTE! This may not be good practice. There are better ways to inserting a TRUENULL value! This actually inserts the word NULL in the database! You may have to look over your final code and determine if my way was the best way. Also, you only have to do this if you have issues trying to insert the data into MySQL.
End Edit.
The only way this post will help you is if in your MySQL database you have NULL set to YES and DEFAULT as NULL. Most databases are not setup this way, it’s probably pretty rare. See end of post.
Recently I ran into an issue with my php script that inserts data into MySQL that has NULL fields. Here is how I fixed it.
To start in my database I have fields that can accept a NULL value, because of this I had to change the way my data was entered into the database. After I created a form to take the data I then ran it through a process to add slashes (in case there were any single quotes, double quotes, or any other non standard character).
For example, I have a field called title in my database, and in my form. Now lets say that the user of the script doesn’t enter in a title but we still want to insert a record. I need to first determine that there is or is not any data.
If your like me you have scoured the internet trying to find a simple php script that will let a user upload an image and then rename the image to something unique. Well I have just the solution.
First, the only real requirement is PHP and a web server (I use Apache).
Create a new file, lets call it ‘image_upload.php’
At the bottom of the page we are going to put in a basic form to give a browse and upload button.
The form name isn’t important. The action is. That is the name of the file that needs to be accessed when the upload button is clicked.
Input type is very important, and so is the name.
Now that we have a starting point go to the top of the file. Just to make it easy I’m going to paste the entire code here then explain it part by part.
To start the if statement at the top is to ensure that the ‘submit’ button was hit before running the script.
The ‘$tmp_name‘ variable is used to get rid of that damn array. $newarray takes the file’s real name (see note below) and explodes the array into several smaller arrays by the ‘.’. For example, if the file uploaded it called ‘best.friends.pic.jpg’ it breaks that name up to ‘best’, ‘friends’, ‘pic’, and ‘jpg’. Trust me, this is important (If you don’t understand how arrays work I recommend doing some research and learning).
The next line I use the count function. This will help in the event there is more than one ‘.’ in the name of the file being uploaded.
Now to create the new name of the file. $fileprefix equals the time of the upload. This works well, it will grab the time from the server and use it for the file name. Then it adds a ‘.’, then adds the suffix of the file (example: jpg)
Time to move the uploaded file. In my example I added the directory before the newly created file name. This will go back 1 directory and then to ‘img/‘.
Lastly, we use the ‘exit();‘ function. This is so that after the file has been uploaded the script stops. If you remove the function it will display the upload form again.
NOTE: There is a reason (although I don’t know it) on why there are 2 arrays. It seems to me that the first ($_FILES[‘thefile’][‘tmp_name’]) holds 2 parts, a pointer for ‘thefile‘ and the temp name php gives files before we do something with it, and the second ($_FILES[‘thefile’][‘name’]) contains the original name of the file.
btw, make sure apache has full access to the folder you are uploading images to.
For example, if this is on your own server check /etc/apache.conf (or httpd.conf) for the user and group apache runs under. This is usually either ‘nobody‘ or ‘apache‘.
If you have SSH into your server (or are sitting infront of it) goto the directory your files are being sent to and type
chown apache.apache img/-R
chown apache.apache img/ -R
This will give both user and group ‘apache‘ access to write files.
p.s. I will be creating another script here that deals with multiple picture uploads.
A little while ago I decided to build a little rss feed for the main site. This way I could have an area for little news information like new pictures. I use the forum for big news like program releases and this blog for cool stuff. So here we go, this is how I built my mini news feed.
The entire thing uses a simple MySQL database, apache, php, and some xml code. To start you MUST edit your mod_php.conf file, look for the line.
See how I have .xml at the end. This is because rss feed use xml, if you don’t add this your php parser will not check your .xml files for php code. Remember you will have to restart your apache server after editing that file.
Now, to make things simple I recommend using phpMyAdmin to help you build a database. After you have installed phpMyAdmin and logged in as root you can create your database.
Once logged in create a new database, lets call it foobar. Create 2 tables ‘admin’ and ‘mininews’. In admin we need 3 Fields,
idx (type 'int(2)', Extra 'auto_increment', put as KEY)
name (type 'tinytext')
pass (type 'tinytext')
Then under mininews
idx (type 'int(100)', Extra 'auto_increment', put as KEY)
news (type 'tinytext')
link (type 'tinytext')
date (type 'timestamp', default 'CURRENT_TIMESPAMP')
Now go to insert a new record in ‘admin’, idx should start at 0, but it doesn’t really matter.
Under name, put a username that you will use to insert new records.
Under pass, put a password you want to use. MAKE SURE YOU SET THE ‘FUNCTION’ IS SET TO PASSWORD! THIS WILL ENCRYPT YOUR PASSWORD!
Go back to the main page with phpMyAdmin and click on the ‘Privileges’ tab. Then create a new user. REMEMBER YOUR USERNAME AND PASSWORD, DO NOT USE THE SAME LOGIN AS ABOVE!
Put in a username, localhost, password, and re-type password. Then click Go, do NOT give that user access over the entire server. On the next screen you can select the database you want the user to have access to, select ‘foobar’.
Only give that user the following privileges under the data area.
SELECT INSERT and UPDATE.
Once done with that you may see an option to update server privileges, if not it may have been done already… I sure hope so.
Now we need some starter php code. This section is used to insert data into the database from the web browser and NOW with phpMyAdmin (altho you are welcome to use it if you so desire).
Here is my mininews_mysql.php file. This will connect to the database for reading and writing.
<?phpdefine('DB_USER','<DB USER>');define('DB_PASSWORD','<DB PASSWORD>');define('DB_HOST','localhost');define('DB_NAME','foobar');$dbc=@mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) OR die('Could not connect to mini news feed database '.mysql_error());mysql_select_db(DB_NAME) OR die('Could not select mini news feed database '.mysql_error());// function for trimming form datafunction escape_data($data){global$dbc;if(ini_get('magic_quotes_gpc')){$data=stripslashes($data);}returnmysql_real_escape_string(trim($data),$dbc);}// end escape data function?>
<?php
define ('DB_USER', '<DB USER>');
define ('DB_PASSWORD', '<DB PASSWORD>');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'foobar');
$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to mini news feed database ' . mysql_error() );
mysql_select_db (DB_NAME) OR die ('Could not select mini news feed database ' . mysql_error() );
// function for trimming form data
function escape_data($data) {
global $dbc;
if (ini_get('magic_quotes_gpc')) {
$data = stripslashes($data);
}
return mysql_real_escape_string (trim($data), $dbc);
}
// end escape data function
?>
Now the file used to add a news feed. I call this one mininews_admin.php
<?php// if submitif(isset($_POST['submit'])){require_once('./mininews_mysql.php');// check that uname and upass work in the db$uname= escape_data($_POST['uname']);$upass= escape_data($_POST['upass']);$query="SELECT name FROM admin WHERE name='$uname' AND pass=PASSWORD('$upass')";$result=@mysql_query($query);$row=mysql_fetch_array($result);if($row){// if a match was made$news= escape_data($_POST['news']);$link= escape_data($_POST['link']);// inset data into the database!$query="INSERT INTO mininews (news, link, date) VALUES ('$news', '$link', NOW() )";$result=@mysql_query($query);// run the queryecho"<h1>Completed</h1>";echo"<a href='http://www.tangorangers.com/mininews.php'>Go back!</a>";}else{// if no match was madeecho"WRONG! If you are not an ADMIN you shouldn't even be trying";echo"Click <a href='http://www.tangorangers.com'>here</a> to go home";exit();}// need auto forward back to mininews.phpob_end_clean();mysql_close();}// main script?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>TangoRangers dev site</TITLE>
</HEAD>
<BODY>
<FORM METHOD='POST' ACTION='./mininews_admin.php'>
<h3>Enter in the fields and be sure to enter username and password to post</h3>
Title: <INPUT TYPE="text" NAME="news" size=40 /><br />
Full URL: <INPUT TYPE="text" NAME="link" size=40 /><br />
<br />
User Name: <INPUT type="text" name="uname" /><br />
Password: <INPUT type="password" name="upass" /><br />
<br />
<INPUT type="submit" name="submit" value="submit" /><br />
<a href="./mininews.php">Go Back</a>
</FORM>
</BODY>
</HTML>
<?php
// if submit
if (isset ($_POST['submit'])) {
require_once ('./mininews_mysql.php');
// check that uname and upass work in the db
$uname = escape_data($_POST['uname']);
$upass = escape_data($_POST['upass']);
$query = "SELECT name FROM admin WHERE name='$uname' AND pass=PASSWORD('$upass')";
$result = @mysql_query ($query);
$row = mysql_fetch_array ($result);
if ($row) { // if a match was made
$news = escape_data($_POST['news']);
$link = escape_data($_POST['link']);
// inset data into the database!
$query = "INSERT INTO mininews (news, link, date) VALUES ('$news', '$link', NOW() )";
$result = @mysql_query ($query); // run the query
echo "<h1>Completed</h1>";
echo "<a href='http://www.tangorangers.com/mininews.php'>Go back!</a>";
}
else { // if no match was made
echo "WRONG! If you are not an ADMIN you shouldn't even be trying";
echo "Click <a href='http://www.tangorangers.com'>here</a> to go home";
exit();
}
// need auto forward back to mininews.php
ob_end_clean();
mysql_close();
}
// main script
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>TangoRangers dev site</TITLE>
</HEAD>
<BODY>
<FORM METHOD='POST' ACTION='./mininews_admin.php'>
<h3>Enter in the fields and be sure to enter username and password to post</h3>
Title: <INPUT TYPE="text" NAME="news" size=40 /><br />
Full URL: <INPUT TYPE="text" NAME="link" size=40 /><br />
<br />
User Name: <INPUT type="text" name="uname" /><br />
Password: <INPUT type="password" name="upass" /><br />
<br />
<INPUT type="submit" name="submit" value="submit" /><br />
<a href="./mininews.php">Go Back</a>
</FORM>
</BODY>
</HTML>
You are free to edit this as you see fit, the only problem I have is after you insert a new feed it shows you what you started with. It’s kind of annoying, but I live with it.
Now for the actual rss feed!
To start, edit your index.php/html file and include this example line in your
function.
That will add the little rss feed button in the address bar of everyone’s favorite web browser (*cough* Firefox).
Now create a file called ‘mininews.xml’. xml is a pretty easy language to work with, it’s layout is as follows
In the actual file you will need to pull data from the database and for that matter, call the mininews_mysql.php file to form the connection to the database. Here is my file (slightly edited).
<?phprequire_once('./mininews_mysql.php');$query="SELECT DATE_FORMAT(date, '%b %D, %Y at %k:%i') AS date, news AS news, link AS link FROM mininews ORDER BY date DESC";$result=@mysql_query($query);//$row = mysql_fetch_array ($result);$rss='<?xml version="1.0" encoding="iso-8859-1" ?>';$rss.='<rss version="2.0">';$rss.='<channel>';$rss.='<title>Site News</title>';$rss.='<link>http://www.tangorangers.com</link>';$rss.='<description>mini news feed</description>';while($row=mysql_fetch_array($result)){$rss.="
<item>
<title>".$row['news']."</title>
<link>".$row['link']."</link>
<description>on ".$row['date']."</description>
</item>";}$rss.='</channel>';$rss.='</rss>';header("Content-Type: text/xml; charset=iso-8859-1");print$rss;?>
<?php
require_once ('./mininews_mysql.php');
$query = "SELECT DATE_FORMAT(date, '%b %D, %Y at %k:%i') AS date, news AS news, link AS link FROM mininews ORDER BY date DESC";
$result = @mysql_query ($query);
//$row = mysql_fetch_array ($result);
$rss = '<?xml version="1.0" encoding="iso-8859-1" ?>';
$rss .= '<rss version="2.0">';
$rss .= '<channel>';
$rss .= '<title>Site News</title>';
$rss .= '<link>http://www.tangorangers.com</link>';
$rss .= '<description>mini news feed</description>';
while($row = mysql_fetch_array($result)){
$rss .= "
<item>
<title>".$row['news']."</title>
<link>".$row['link']."</link>
<description>on ".$row['date']."</description>
</item>";
}
$rss .= '</channel>';
$rss .= '</rss>';
header("Content-Type: text/xml; charset=iso-8859-1");
print $rss;
?>
Now this will pull EVERY feed, no limits, so if you have a lot you may want to add in a limiter. Look at the $query line, and add ‘LIMIT #’ at the end, replace # with the actual number.
And that should do it. I think, I don’t think I missed anything, if I did… oops… I’ll fix it. Until next time ^_^