Posts tagged ‘php’

Dynamically add form fields using javascript and DOM with dynamic post method

Lets say you need to add some extra text fields but you don’t want to write a bunch of code. I not only have how to quickly and easily add the input fields, but also how to take the data and put in into a MySQL DB!

I start with creating the DB. Lets call the table ‘phone’. We need 3 rows. ‘idx’ int(10) with Auto Increment and primary key. ‘name’ varchar(30), and ‘numb’ varchar(20). You can setup the db how ever you choose. I create the idx so that I have a key field.

Now we need some javascript.

var counter = 0;
Start a counter. Yes, at 0
function add_phone() {
    counter++;
// I find it easier to start the incrementing of the counter here.
    var newFields = document.getElementById('add_phone').cloneNode(true);
    newFields.id = '';
    newFields.style.display = 'block';
    var newField = newFields.childNodes;
    for (var i=0;i<newField.length;i++) {
        var theName = newField[i].name
        if (theName)
                newField[i].name = theName + counter;
// This will change the 'name' field by adding an auto incrementing number at the end. This is important.
        }
        var insertHere = document.getElementById('add_phone');
// Inside the getElementById brackets is the name of the div class you will use.
        insertHere.parentNode.insertBefore(newFields,insertHere);
}

Now I like to put that in a seperate .js file, but you can add it to your HTML HEAD tag.

Next we need to build the form.

<form name="add_a_phone" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<fieldset>
<div id="phone">
    <input type="text" name="phone_0" value="" />
    <input type="text" name="phone_num_0" value="" /><br>
</div>
<div id="add_phone" style="display: none;">
    <input type="text" name="phone_" value="" />
    <input type="text" name="phone_num_" value="" /><br>
</div>
<input type="button" id="add_phone()" onclick="add_phone()" value="Give me more fields!" /><br>
<input type="submit" name="submit" value="submit" />
</fieldset>
</form>

Notice how in the input button field that the ‘id’ and ‘onclick’ are the same. That’s important, and yes you do need the brackets for some reason.
Also note that the form name can NOT be the same as any div id!!! I keep making that mistake.
You will need some way of checking how many fields were added when you get to your ‘if(isset($_POST[‘submit’))’ statement. This gets a little messy.
Because I like my forms to go back to this page and check if submit was clicked we need to put some php code at the very top.

<?php
    if(isset($_POST['submit']))
    {
        echo "You clicked submit!<br>";
        echo "Here is your data<br>";
        echo "<br>";
        if ($_POST['phone_num_0'])
        {
                $continue = FALSE;
                $i = 0;
                while ($continue == FALSE)
                {
                    if (isset($_POST['phone_'.$i]))
                    {
                    echo $_POST['phone_'.$i] . " = " . $_POST['phone_num_'.$i] . "<br>";
                    $phone = $_POST['phone_'.$i];
                    $phone_num = $_POST['phone_num_'.$i];
                    $query = "INSERT INTO phone (idx, name, numb) VALUES ('NULL', '$phone', '$phone_num')";
                    $result = mysql_query($query);
                }
                else
                {
                    $continue = TRUE;
                }
                $i++;
            }
        }
    }
?>

Obviously I left out some information. Like connecting to your DB. I’m assuming you already know how to do that.

I first wrote this on my main page. This post is almost a copy/paste from the main page. I like adding it to the blog since it gets better indexing from search engines and hopefully the information will be useful to you. On the main page there is also a working example so you can see how it all ties in. Check it out Here

Questions?

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.

Using PHP to upload an image and rename it.

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.

<form action="./image_upload.php" enctype="multipart/form-data" method="post">
Select Image to upload
<input name="thefile" type="file" />
<input name="submit" type="submit" value="upload" />
</form>

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.

if(isset($_POST['submit']))
{
 
	$tmp_name = $_FILES['thefile']['tmp_name'];
	$newarray = explode( ".", $_FILES['thefile']['name']);
	$thecount = count($newarray);
	$fileprefix = time() . "." . $newarray[$thecount - 1];
	move_uploaded_file($tmp_name, "../img/$fileprefix");
	exit();
}

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

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.

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