Posts tagged ‘mysql’

Insert MySQL query in php with NULL

EDIT: 03/01/2009
NOTE! This may not be good practice. There are better ways to inserting a TRUE NULL 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 ($_POST['title'])
{
     $title = addslashes($_POST['title']);
}
else
{
     $title = "NULL";
}

Notice that I put NULL in quotations. If you do not quote it you will clear out the variable. This will cause issues in the INSERT query to MySQL.

The MySQL query might look something like this.

$result = mysql_query($query = "INSERT INTO table_name (name, title) VALUES ('$name', '$title')");

I know this doesn’t make much sense, but it’s the way I had to do it because of the way my database was setup. Here is the entire php file.

<?php
if (isset($_POST['submit']))
{
  if (isset($_POST['name']))
  {
    $name = addslashes($_POST['name']);
    if (isset($_POST['title']))
    {
      $title = addslashes($_POST['title']);
    }
    else
    {
      $title = "NULL";
    }
  $result = mysql_query($query = "INSERT INTO table_name (name, title) VALUES ('$name', '$title')");
  }
  else
  {
    echo "Enter a Name!<br />";
  }
}
?>
<form name="form1" action = "<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype='multipart/form-data'>
     <input name="name" type="text" value="name" />
     <input name="title" type="text" value="title" />
     <input name="submit" type="submit" value="submit" />
</form>

In the Database, using something like PHPMyAdmin External popup link you might see something like this.

Field———-Type—————–Collation———Attributes——Null——Default——Extra
name——-varchar(30)—-utf8_unicode_ci——–None———-No
title———varchar(30)—-utf8_unicode_ci——–None———-Yes——–NULL

If so you will need to quote your NULL before inserting the data into MySQL. (Sorry that doesn’t line up very well)
Maybe this way will help.

My new rss mini news feed

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.

AddType application/x-httpd-php .php .html .htm .xml

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.

<?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 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

<item>
<title></title>
<link></link>
<description></description>
</item>

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).

<?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 ^_^