Click here to Skip to main content
15,867,568 members
Articles / Web Development / HTML

PHP A to Z

Rate me:
Please Sign up or sign in to vote.
4.89/5 (35 votes)
25 Jun 2013CPOL11 min read 86.6K   49   19
Tutorial for developing in PHP

Introduction

A...

They say that PHP, C# and Java are most wanted and most preferable programming languages. Why is so for PHP? PHP is as by definition server-side scripting language. It is quite easy but very powerful language. Nowadays, web is more and more expanding and need for web development is extreme. There are plenty of website designs/templates from the ‘box’ which can be bought, rent or even found free. Of course some of these websites are with plenty of features and really amazing. Usually for a specific project, or some innovation, it is quite hard to find adequate template or already made webpage. Designing live php webpage/website/webplatform/webportal from scratch is not easy job at all.

In this article I will lead you through basic things needed for you to start developing your own php web portal, teaching you some basic html, teaching you basic programming, validating form inputs, reading writing and editing mysql database etc.  

server

For beginning of course you should host your website somewhere. Best solution is buying webhosting package from some specialized hosting company (I won’t mention here any). You can buy let’s say Linux package in which there is already installed 1. http web server, 2. mysql server and 3. php itself.

If you need to have your own server than you can setup all these quite easy through dedicated packages, for example WAMP for Windows, MAMP for Mac OS X, LAMP for Linux etc. Let’s just mention that these packages will install and usually configure all things we need: Apache http server, mysql server and php.

before starting learning php

Before starting php programming lessons, you need to know some other things.

First thing to know is HTML tags. HTML tag or element is actually keyword which is inside angle brackets <…> and they are like ‘commands’ to web browser, for example if <b> tag is present, any text displayed after this tag will be in bold. Like in our word processor every block of text we want to let’s say make bold has to be selected so there will be starting and ending point, so if we want to make some text bold we should start bold, put text and then end bold, like this: <b>this is bold text</b> where output in browser will be this is bold text, of course it will be displayed without beginning and ending tag. Usually html tags go in pair like: <...>something in here</…> where slash is saying ‘here is ending of tag block’.

If you want to develop php website, you should definitely learn perfectly table html tags: <table>, <tr> and <td>, go right now and learn them if you don’t know them. Immediately after this, go learn forms in html, we will need these for entering data like Name, City, Price, add pictures or files etc…

Second thing you should know are databases. Of course databases are ‘oceans’, but without them there would not be any of accounting software, supermarket software, telephone databases etc. For beginning knowing to create/edit table, using MySQL phpMyAdmin and understanding simple ‘SELECT’ SQL command would be enough.

Third basic thing to know is FTP. FTP stands for File Transfer Protocol, it is actually a software which enables connection and file transfer between your computer and server, so through FTP we will send our PHP program to our server.

Fourth thing is choosing your PHP editor. I personally use Notepad++ which is easy to use and is free. It also has integrated FTP which is simple and very useful, so after writing some code, by just pressing ‘Upload file’ button, your file will be immediately sent to server so you can test it right away.

Fifth and not last thing is using java script inside our produced html. Just let me clarify to you that php code stays and executes in server and is not accessible by user, but java script code is executed by your web browser and is accessible by anyone.

our first php code 

First thing to know is where to put your code. php code goes inside <?php … ?> tag, so anything written inside this code should be php. Let’s see one very simple example:
PHP
<span style="font-size: 11pt; line-height: 115%; font-family: "Calibri","sans-serif";"><?php
<span>    </span>echo ‘This is first line<br>’;
<span>    </span>echo ‘This is second line’;
?></span>

echo command is very simple and very important command, it sends text to our web browser, in this case two lines of text. You can see that I used <br> at the end of first line, this is ‘break’ (new line) html tag, so because of this second line of text would be displayed beneath of first line.

You probably noticed that at the end of echo command there is semicolon “;” sign, actually this is the rule of C language and it should be at the end of every command.

variables and arrays

Variables are one of most important things in programming languages. So what are variables? Remember school? X is variable, Y is variable, Z is variable. Variable is called because it can be of any value, so in one moment it can be 1 and in second moment can be 2. Variables in programming can be also strings (texts). Example: x=55, x=”John Doe”. In php, every variable should begin with $ sign and of course don’t forget semicolon ‘;’. Let’s see an example:

PHP
<?php
    $myName="John Doe";
    $myAge=55;

    echo ‘My name is ’;
    echo $myName;
    echoand I am ’;
    echo $myage;
    echo ‘ years old.’;
    $afterYears=10;
    $myAge+=$afterYears;
    Echo ‘ After ’. $afterYears.’ years, I will be ‘.$myAge.’ years old.’;
?> 

We could put first five echo’s in one echo like this: echo ‘My name is ‘.$myName.’ and I am ‘.$myage.’ years old.’;

Dot sign “.” means addition, so it means “add .$myName to previous sting”

Addition of two variables is done through + sign, instead of doing +=, I could do simply:

PHP
$myAge=$myAge+$afterYears; // (which is like in school: X=X+Y)

I could use “ instead of ‘ in echo command, but plenty of html tags use “ in it, like for example table tag: <table  border="1" width="100%">, so it is easily written through

PHP
echo<table <span> </span>border="1" width="100%">’; 

Arrays are variables but organized/put in series. Let’s see an example:

PHP
$citiesArray = array();     // initializing array
$citiesArray[]=’New York’;   // adding element 0 to array 
$citiesArray[]=’Washington DC’;   // adding element 1 to array
$citiesArray[]=’Los Angeles’;   // adding element 2 to array
$citiesArray[]=’Wyoming’;   // adding element 3 to array
$citiesArray[]=’San Antonio’;   // adding element 4 to array
$numberOfCities=5; 


So we created here string array which contains 5 elements. Elements of an array are accessed through brackets, like this:

PHP
echo $citiesArray[0]; 

The output will be New York, because elements of arrays always begin at position 0. Two slashes // means ‘comment’ and nothing after two slashes till new line is not executed.

start the session

Sadly values of our variables and arrays disappear after php ends executing, so if we need to keep track of value of our variable, we should use session variables. Session is in fact a block of code which starts when web browser opens and its life is until that web browser closes or session is closed. Example of session is our web e-mail. Session starts when we click login button after we entered valid username and password. Session ends when we click on logout button or we close that web browser. Variable which needs to be tracked and reused within the session is our email address, example johndoe@myemailprovider.com

In php, sessions are really very simple. At the very beginning of php code we should declare session start, like this:

PHP
<?php
<span>    </span>session_start();
<span>    </span>….
?> 

Session variable is declared after session_start command, but beware, it has to be declared only first time session started, example after login button and if user entered valid username and password. Example of session variable:

PHP
$_SESSION[‘userLoggedIn’] =’johndoe@myemailprovider.com’;

what if 

Another most important thing in programming is checking things. The simplest way to check something is through if command. Example:

PHP
if(isset($_SESSION[‘userLoggedIn’])) {
<span>    </span>echo ‘User ‘.$_SESSION[‘userLoggedIn’].’is logged in.’;
<span>    </span>…
}
else {
<span>    </span>echo ‘No user is logged in!’;
<span>    .</span>…
} 

So in this case if session variable ‘userLoggedIn’ is set, it will display text that that user is logged in, in contrary if that session variable is not set (else command), ‘No user is logged in!’ text will be displayed. Other way of checking variables is switch/case command. Example:

PHP
$myStatus=1;
switch($myStatus) {
    case 0:
        echo ‘I am not married.’;
        ….
        break;
    case 1;
        echo ‘I am married.’;
        ….
        break;
    ….
}

So in this scenario we did checking against variable $myStatus, and we executed some different code for different values, for example if variable is 1 then text ‘I am married.’ will be displayed.

java scripts

Java script functions should be inserted inside html tag <script Language="Javascript"><!-- ……  //--></script> in top of the page but outside of php tag and after session start. Example:

HTML
<?php
<span>    </span>session_start(); // do not forget that session start should be at top of everything
?>

<script Language="Javascript">
<!--<span>  </span>
<span>    </span>function myfunction()
<span>    </span>{
<span>        </span>….
<span>    </span>}
//-->
</script>

Java script is used for example: for validating form fields, creating interactive buttons, doing some screen animation like moving alien ship, etc. Java language is very similar to php and is simple to learn. Java scripts are called from: example html tags like within <input …> tag:

PHP
echo<input type="text" name="nameAndLastName"
value="'.htmlspecialchars($myname, ENT_QUOTES).'" onChange=" validateempty
(this,5,'."'Insert your name and last name'".')">’;

In this case when we change field (onChange), java script function validateempty() will be called and it will actually check if entered field is more or equal than 5 characters.

You can see in this example that I used htmlspecialchars() function which is in fact very important function which will prevent one type of attacks for our databases.

mysqli, and loops

mysqli is in fact new way of accessing and working with databases in mysql through php. Let’s read some data from our database:

PHP
$DB_HOST=’myhost’; // example localhost
$DB_USER=’mysqlusername';
$DB_PASS=’mysqluserpassword’;
$DB_NAME=’mydatabasetouse’;
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/// check the connection to database
if (mysqli_connect_errno()) {
                printf("Connection failed: %s\n", mysqli_connect_error());
                exit();
}
$query = "SELECT * FROM MyCompanies where ID>0";
if ($myresult = $mysqli->query($query)) {  // is there any records found?
                while ($row = $myresult->fetch_assoc()) {
                                printf ("%s (%s)\n", $row["Name"], $row["Address"]);
                }
                $myresult->free();
}
$mysqli->close();

In this example we opened a database through mysqli command, did a simple SELECT query, checked if any records are found and looped through every record returned and displayed Name and Address fields. At the end we freed resources of results and closed database object.

printf command is similar to echo, but inside of quotes you can put %s or %d which than are replaced by string variable (%s) and number variable (%d) that are after first parameter delimited by comma ‘,’ example:

PHP
printf("My name is %s and I am %d years old.", $myName,$myAge);

Inside while command, command fetch_assoc() is executed on $myresult. With this command we retrieved data from our database and actually filled array $row[] with table field elements, we displayed fields by searching by their respective names: $row["Name"], $row["Address"] …

You can see that I used while command, which is similar to for command and are very important commands in programming languages. They are used to ‘loop’/repeat a block of code inside of { } brackets until condition is true. Let’s see an example of for command:

PHP
for($i=0;$i<100;$i++) {
<span>    </span>echo $i+1.’, ‘;
}

In this example numbers from 1 to 100 will be displayed since for command will be repeated until $i is less than 100. 

headers and footers

You’ve seen in web pages that header and footer is always same and it repeats. I personally prefer to create two separate .php files, one for header and the other for footer. In header I usually put logo and selection menu, while in footer I put company information, developer credit and similar info’s. You can put in header variables which you can use them in your main page and also footer, like for example background color, text color, font etc. Including header and footer in your main page (usually in your index.php page) is very simple, just write: include "header.php"; after session_start() command, it is same for your footer: include "footer.php"; at the end of your main php file but before ?> ending tag.

In example below you can find actual working header from my www.autosalloni.com webpage. It includes logo, some information on top right corner, weather information for city near me and working menu. All formatting are done through tables with invisible borders, so tables are really ‘must know’.

header.php   

PHP
<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>autosalloni.com</title></head>
<body bgcolor="#DFDFDF" leftmargin="0" rightmargin="0" topmargin="0">
<table border="0" width="100%" height="100" bgcolor="#800000"><tr><td width="17">&nbsp;</td><td><b><font face="Arial" size="7" color="#FFFFFF">autosalloni.com</font></b></td>
<td width="170"><font color="#FFFFFF" style="font-size: 8pt" face="Arial">Send us by email your opinion about this php tutorial.<a href="mailto:info@autosalloni.com?subject=New opinion"><font color="#FFFF00">info@autosalloni.com</font></a></font></td>

<td align="right" bgcolor="#C0C0C0" width="1"><script src='http://netweather.accuweather.com/adcbin/netweather_v2/netweatherV2.asp?partner=netweather&tStyle=whteYell&logo=0&zipcode=EUR|CS|YI003|PRISTINA|&lang=eng&size=7&theme=gold&metric=1&target=_self'></script>
</td></tr></table>
<table border="0" width="100%" height="50" cellspacing="0"><tr>
<?php
$mymenucolor="#0068CF";
$mymenucolorselected="#00689F";
echo "<td bgcolor=$mymenucolor width=\"20\">&nbsp;</td>";


$mycategory=1;
if(intval($_GET['category'])>0)
  $mycategory=intval($_GET['category']);
$mycolor1=$mymenucolor;
if($mycategory==1)
  $mycolor1=$mymenucolorselected;
$mycolor2=$mymenucolor;
if($mycategory==2)
  $mycolor2=$mymenucolorselected;
$mycolor3=$mymenucolor;
if($mycategory==3)
  $mycolor3=$mymenucolorselected;
$mycolor4=$mymenucolor;
if($mycategory==4)
  $mycolor4=$mymenucolorselected;
$mycolor5=$mymenucolor;
if($mycategory==5)
  $mycolor5=$mymenucolorselected;
echo "<td bgcolor=$mycolor1 width=\"1\"><b><font color=\"#FFFFFF\" face=\"Arial\"><a href=\"?category=1\" STYLE=\"TEXT-DECORATION: NONE\"><font color=\"#FFFFFF\">AUTOSALOONS</font></a></font></b></td>";		
printf("<td bgcolor=$mymenucolor width=\"20\">&nbsp;</td>");
echo "<td bgcolor=$mycolor2 width=\"1\"><b><font color=\"#FFFFFF\" face=\"Arial\"><a href=\"?category=2\" STYLE=\"TEXT-DECORATION: NONE\"><font color=\"#FFFFFF\">AUTOPARTS</font></a></font></b></td>";
printf("<td bgcolor=$mymenucolor width=\"20\">&nbsp;</td>");		
echo "<td bgcolor=$mycolor3 width=\"1\"><b><font color=\"#FFFFFF\" face=\"Arial\"><a href=\"?category=3\" STYLE=\"TEXT-DECORATION: NONE\"><font color=\"#FFFFFF\">AUTOSERVICES</font></a></font></b></td>";		
printf("<td bgcolor=$mymenucolor width=\"20\">&nbsp;</td>");

echo "<td bgcolor=$mycolor4 width=\"100\"><b><font color=\"#FFFFFF\" face=\"Arial\"><a href=\"?category=4\" style=\"text-decoration: none\"><font color=\"#FFFFFF\">RENT A CAR</font></a></font></b></td>";
printf("<td bgcolor=$mymenucolor></td>");
echo "<td bgcolor=$mycolor5 width=\"150\"><p align=\"right\"><b><a href=\"?category=5\" STYLE=\"TEXT-DECORATION: NONE\"><font face=\"Arial\" color=\"#FFFF00\">SELL YOUR CAR </font></a></b></td>";
printf("<td bgcolor=$mymenucolor width=\"20\">&nbsp;</td>");
echo "<td bgcolor=$mymenucolor>&nbsp;</td>"
echo<td bgcolor="#333333" width="170" align="center">’;
echo ‘<table border="0" width="100%" cellspacing="0" cellpadding="0" height="15">’;
echo ‘<tr><td></td></tr></table></td>’;
echo "<td bgcolor=$mymenucolor width=\"20\">&nbsp;</td></tr></table>";

As you can see, I’ve used five variables for five different menu background colors (categories). I’ve passed selected menu through php ? hyperlink like: index.php?category=2, so when category (or menu item) 2 is clicked, number 2 will be passed to next time page loads and it will be read by $_GET: $mycategory=intval($_GET['category']);. Function intval() guarantees us that number is passed and not any text, it converts strings to numbers.

forms

Forms are used to get data from our users, for example item name, manufacturer, price, pictures. In example below I will show you how to get these fields from user and simple image upload technique I use in my web portal in which you can upload image which will be automatically previewed and I added delete button so last image can be deleted if uploaded by mistake, also will show you validation of fields by java script and php itself. HTML form part should be inserted somewhere before end of your php file. It should be there because checking of our submission values should be done before our HTML form code. Fields are read from users by <input …> tag. At the end when save item button is clicked, database will be updated with number of images uploaded so the application will know how many images are for each item. Of course this is not perfect solution, but it is one of possible solutions and easy to learn. Including just a little bit more java script on field validation and upload, some things could be done much better and easier, but all those I leave for you.

HTML
<span style="font-size: 11pt; line-height: 115%; font-family: "Calibri","sans-serif";"></span> <?php
    session_start();
include "header.php";
$mybgcolor='#0068CF';
?>

<script Language="Javascript">
<!--  
function emptyvalidation(mytext, mylength, alerttext)
{
  if (mytext.value.length<mylength)
    {if (alerttext) {alert(alerttext);} return false;}
    else
    {return true;}
}
//-->
</script>
<?php
if(!isset($_SESSION['allpictures'])) {
    $_SESSION['allpictures'] = 0;
    $_SESSION['AdvID']=0;
}
    if(!isset($_SESSION['allManufacturers'])) {
  // Read Manufacturers from DB and put them to array so we read from mysql only once
  $ManufacturersArray = array();
      $link = mysql_connect($DB_HOST, $DB_USER, $DB_PASS);
      if (!$link) {
        printf("Connect failed: %s\n", mysql_error());
        exit();
      }
      mysql_select_db($DB_NAME,$link);
      $myquerystring=sprintf("SELECT * FROM `Manufacturers` WHERE ManufacturerID>0 order by ManufacturerID ");
      $result = mysql_query($myquerystring,$link);
      $allManufacturers = mysql_num_rows($result);
      if($allManufacturers>0) { // if there are some manufacturers found, continue
	    $ManufacturersArray[]=’Select Manufacturer’;
 	    while ($myrow = mysql_fetch_array($result)) {
	      $ManufacturersArray[]=$myrow["ManufacturerName"];
	    }
      } 
	  $_SESSION['allManufacturers']=$allManufacturers; // copy local array to session array
	  $_SESSION['ManufacturersArray']=$ManufacturersArray; // copy local array to session array
      mysql_close($link);
	}
$allfields=3; // item name, manufacturer, price
$ip = $_SERVER["REMOTE_ADDR"]; // ip address of our user
    // error message are at beginning empty
    $itemErr="";
    $listManufacturerErr="";
    $priceErr="";
    // Here we read last values from passing variables through _POST method
    $myitem=$_POST["item"];
    $mylistManufacturer =$_POST["listManufacturer"];
    $myprice=$_POST["price"];
$myOK=0;
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
      if (strlen($_POST["item"])<5) { // if ‘item’ has less than 5 characters it will generate error
          $emriErr=" *";
      }
      else {
          $myOK++; // if everything ok myOK variable will increase by one
      }
    if ((int)$_POST["listManufacturer "]==0) { // if manufacturer selection is 0, it is not selected at all, error
      $listManufacturerErr=" *";
    }
    else {
      $myOK++; // if everything ok myOK variable will increase by one
    }
    if ((int)$_POST["price"]<=0) { // if price is less or equal to 0 then it is not written, error
      $priceErr=" *";
    }
    else {
      $myOK++; // if everything ok myOK variable will increase by one
    }
}
// if button send item is clicked, update database and reset everything to 0 
if (array_key_exists('newpost', $_POST) && $myOK>=$allfields && $_SESSION['allpictures'] > 0) {
echo ‘Thank you for inserting another item!<br><br>’;
   $mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
   // check connection
if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
}
$query = "UPDATE `Items` SET `NumberOfImages`='".$_SESSION['allpictures']."', `ItemSubmited`='1' WHERE  `Item_ID` ='".$_SESSION['AdvID']."' LIMIT 1 ;";
				$stmt = $mysqli->prepare($query);
				$stmt->execute();
				$stmt->close();
    // Reset variables
    $myOK=0;
    $myitem="";
    $myprice=0;
    $mylistManufacturer=0;
    $_SESSION['allpictures']=0;
    $_SESSION['AdvID']=0;
}

$df=0;
// if delete last image button is clicked, decrement one image
if (array_key_exists('deletelast', $_POST) && $myOK>=$allfields && $_SESSION['allpictures'] > 0) {
  $_SESSION['allpictures']--;
  $df++;
}

// if all fields are entered and upload picture is clicked, get inside...
if (array_key_exists('uploadfoto', $_POST) && $myOK>=$allfields) { 
    define ('MAX_FILE_SIZE', 1024 * 1000); // 1000kb filesize limit
    $permitted = array('image/jpeg', 'image/pjpeg', 'image/png'); // accept jpeg and png only
  if (in_array($_FILES['image1']['type'], $permitted) && $_FILES['image1']['size'] > 0 && $_FILES['image1']['size'] <=MAX_FILE_SIZE) {
    switch($_FILES['image1']['error']) {
      case 0:
        // move the file to the upload folder and rename it		$file='adv_'.strval($_SESSION['AdvID']).'_'.strval($_SESSION['allpictures']+1); // assuming that upload is ok
		// if already exists same file, delete it first because he is resending this file
		$completeFileName=$_SERVER['DOCUMENT_ROOT'] .'/uploads/'.$file;
		if(file_exists($completeFileName)) {
		  unset($completeFileName);
		}
		// move and rename file
        $success = move_uploaded_file($_FILES['image1']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] .'/uploads/'.$file);
        if ($success) {
  // increase picture number +1 after successfully moved and renamed
          $_SESSION['allpictures']++;
        }
        break;
    }
  }
}
if (!array_key_exists('newpost', $_POST)) {
	echo '<form action="'.$PHP_SELF.'" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">';
	echo '<table border="0" width="700"  cellspacing="0" cellpadding="0" >';
	echo '<tr><td bgcolor="'.$mybgcolor.'"><b><font color="#FFFFFF" face="Arial" size=4> Item data</font></b></td></tr></table>';
	echo '<table border="1" width="700"  bgcolor="#ffffff" cellspacing="0" cellpadding="0" style="border: 1pt solid #000000; border-Collapse:collapse">';

// Item name field
echo '<tr><td><table border="0" width="100%">';
echo '<tr><td width="65" bgcolor="#808080"><font color="#FFFFFF">Item</font></td>';
echo '<td>';
if($myOK>=$allfields) {
  echo $myitem;
  echo '<input type="hidden'; // disable input because already is inserted
}
else {
  echo '<input type="text';
}
echo '" name="item" value="'.htmlspecialchars($myitem, ENT_QUOTES).'" onChange="emptyvalidation(this,5,'."'Please write item name'".')"><font color="#FF0000">'.$emriErr.'</font></td>';

echo '<td>';
if($myOK>=$allfields) {
  echo $_SESSION['ManufacturersArray'][$mylistManufacturer];
  echo '<input type="hidden"'; // disable input because already is inserted
  echo ' name="listManufacturer" value="'.htmlspecialchars($mylistManufacturer, ENT_QUOTES).'">';
}
	else {
	  echo '<select name="listManufacturer">';
	  for($myc=0;$myc<=$_SESSION['allManufacturers'];$myc++) {
		echo '<option';
		if($myc==$mylistManufacturer)
		  echo ' selected'; // this line is to set default item selected
		echo ' value="'.$myc.'">'.$_SESSION['ManufacturersArray'][$myc].'</option>';
	  }
	  echo '</select>';
	  echo '<font color="#FF0000">'.$listManufacturerErr.'</font>';
	}
	echo '<td width="100" bgcolor="#808080"><font color="#FFFFFF">Price</font></td>';
	echo '<td>';
	if($myOK>=$allfields) {
	  echo $myprice;
	  echo '<input type="hidden'; // disable input because already is inserted
	}
	else {
	  echo '<input type="text';
	}
	echo '" name="price" value="'.htmlspecialchars($myprice, ENT_QUOTES).'" size=7><font color="#FF0000">'.$ priceErr.'</font></td>';
	echo '</td></tr></table>';
	echo '</table>';
	if($myOK>=$allfields) {
		if($_SESSION['AdvID']==0) {
		// add new record to database and keep that records number for editing
			$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
// check connection
if (mysqli_connect_errno()) {
	printf("Connect failed: %s\n", mysqli_connect_error());
	exit();
}
$query = "INSERT INTO  `Items` (  `Item` ,  `Manufacturer` ,  `Price`) VALUES ( ?, ?, ?);";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('sdd', $myitem, $mylistManufacturer, $myprice);
$stmt->execute();
$_SESSION['AdvID']=$mysqli->insert_id;
$stmt->close();
$mysqli->close();
}
echo '<table border="0" width="700" bgcolor="#ffffff"  cellspacing="0" cellpadding="0" >';
echo '<tr><td bgcolor="'.$mybgcolor.'"><b><font color="#ffffff" face="Arial" size=4> Insert pictures (at least one picture - max.1Mb per picture)</font></b></td></tr></table>';
 echo '<table border="1" width="700" bgcolor="#ffffff"  cellspacing="0" cellpadding="0" style="border: 1pt solid #000000; border-Collapse:collapse">';
echo '<tr><td><table border="0" width="100%">';
echo '<tr><td width="65" bgcolor="#808080"><font color="#FFFFFF">Add pic.</font></td>';
echo '<td><input type="file" name="image1" id="image1" onchange="file_selected = true;" />';
// not more than 7 images can be uploaded
if($_SESSION['allpictures'] < 7) {
  echo '<input type="submit" name="uploadfoto" id="uploadfoto" value="Send pic."/>';
}
echo '</td></tr></table></td></tr>';
if($df>0) {
  if($_SESSION['allpictures']>0){
    // create table for pictures
    echo '<table border="0" ><td></td></table>';
    echo '<table border="0" width="1" style="border-right:1pt solid #C0C0C0; border-bottom:1pt solid #C0C0C0; border-Collapse:collapse; border-left-style:solid; border-left-width:1pt; border-top-style:solid; border-top-width:1pt"><tr>';
    // Displaying uploaded pictures
    for($i=0;$i<$_SESSION['allpictures'];$i++) {
       $file=strval($_SESSION['AdvID']).'_'.strval($i+1);
echo '<img src="./uploads/adv_'.$file.'" width="100" height="75""></td>';
}
if($_SESSION['allpictures'] > 0) {
echo '<input type="image" name="deletelast" value="deletelast" alt="Delete last pic."  src="delete.png" >';
}
echo '</tr></table><br>';
}
}
}
echo '<table border="0" width="700" bgcolor="#ffffff"  cellspacing="0" cellpadding="0" ><tr><td bgcolor="'.$mybgcolor.'">';
echo '<p align="center">';
if($_SESSION['allpictures']==0) {
  if($myOK>=$allfields) {
	  }
 else {
echo '<input type="submit" name="uploadbutton" id="uploadbutton" value="';
echo 'Continue';
echo '" onclick="this.disabled=true;this.value="Sending...";this.form.submit();"/>';
}
}
else {
   echo '<input type="submit" name="newpost" id="newpost" value="Save item"/>';
}
echo '</td></tr></table>';
echo '</form>';
include "footer.php";
?>

Z...    

Oh yes, from A to Z, if you try to learn something from A to Z, than be prepared to read dozens of books and spend years and still not learn everything. I tried to show you some basic techniques and give you some advices on php and web development. I encourage you to get started and test things by yourself. Don’t give up, give it a try, it is not necessary to be perfect in this because no one is, simply learn something that you can really use in your work, or do it for fun :).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Net Media - Kosovo
Albania Albania
Software developer since 1988 in many many languages: Basic, Assembler, Clipper, Visual Basic, C, C#, PHP... Plenty of experience in development, design and databases. Currently working on some iPhone applications projects. Net Media - Gjilan-Kosovo.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Manish Langa4-Sep-13 21:08
Manish Langa4-Sep-13 21:08 
QuestionExcellent article Pin
Greg Russell22-Jul-13 23:50
professionalGreg Russell22-Jul-13 23:50 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA13-Jul-13 20:56
professionalȘtefan-Mihai MOGA13-Jul-13 20:56 
GeneralRe: My vote of 5 Pin
Gazmend Jakupi21-Jul-13 21:51
professionalGazmend Jakupi21-Jul-13 21:51 
GeneralMy vote of 5 Pin
nullpointer8-Jul-13 4:39
nullpointer8-Jul-13 4:39 
GeneralRe: My vote of 5 Pin
Gazmend Jakupi21-Jul-13 21:51
professionalGazmend Jakupi21-Jul-13 21:51 
SuggestionBetter formatting Pin
nullpointer8-Jul-13 4:38
nullpointer8-Jul-13 4:38 
GeneralMy vote of 5 Pin
Andres Fabrizio1-Jul-13 6:36
Andres Fabrizio1-Jul-13 6:36 
GeneralRe: My vote of 5 Pin
Gazmend Jakupi2-Jul-13 1:51
professionalGazmend Jakupi2-Jul-13 1:51 
Questionphp to excel Pin
ABHISHEKk199128-Jun-13 17:04
ABHISHEKk199128-Jun-13 17:04 
QuestionMy Vote 5 Pin
User 1006066526-Jun-13 1:38
User 1006066526-Jun-13 1:38 
AnswerRe: My Vote 5 Pin
Gazmend Jakupi26-Jun-13 2:15
professionalGazmend Jakupi26-Jun-13 2:15 
GeneralMy vote of 5 Pin
S.P.Tiwari25-Jun-13 19:44
professionalS.P.Tiwari25-Jun-13 19:44 
GeneralRe: My vote of 5 Pin
Gazmend Jakupi26-Jun-13 2:16
professionalGazmend Jakupi26-Jun-13 2:16 
GeneralOMG Pin
brooNo25-Jun-13 10:04
brooNo25-Jun-13 10:04 
GeneralRe: OMG Pin
User 1006066526-Jun-13 1:29
User 1006066526-Jun-13 1:29 
GeneralRe: OMG Pin
GregoryW29-May-16 21:00
GregoryW29-May-16 21:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.