Wednesday, April 27, 2011

Wednesday April 27 2011

Finished with the PHP class, have one more week of classes/finals to go. When I am done with that I can start work on the PHP dataminer, see how that goes. Need to start looking at vb.net again as well.


<html>
<head>
<title>Search example</title>
<script type="text/javascript">
function checkSearch()
{
if(!document.getElementById || !document.createTextNode) {return;}
if(!document.getElementById('search')){return;}
var searchValue = document.getElementById('search').value;
if(searchValue=='')
{
alert("Please enter a search term");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form action='sitesearch.php' method='post' onsubmit='return checkSearch();'>
<p>
<label for="search">Search this site:
<input type="text" id="search" name="search" />
<input type="submit" value="Search" />
</p>
</form>
</body>
</html>




<head>
<title>Data Example</title>
<script type="text/javascript">
function checkDate()
{
if(!document.getElementById || !document.createTextNode) {return;}
if(!document.getElementById('date')){return;}
// define a regular expression to check the date format
var checkPattern = new RegExp("\\d{2}/\\d{2}/\\d{4}");
//get the value of the current date entry field
var dateValue=document.getElementById('date').value;
//if there is no date entered, don't send the format
if(dateValue='')
{
alert('Please enter a date');
return false;
}
else
{
//tell the user to change the date syntax either until
//she presses cancel or entered the right syntax
while(!checkPattern.test(dateValue) && dateValue!=null)
{
dateValue = prompt("Your date was not in the right format. " + "Please enter it as DD/MM/YYYY.", dateValue);
}
return dateValue != null;
}
}
</script>
</head>
<body>
<h1>Events search</h1>
<form action="eventssearch.php" method="post" onsubmit="return checkDate();">
<p>
<label for="date">Date in the format DD/MM/YYYY:</label><br/>
<input type="text" id="date" name="date" />
<input type="submit" value="check" />
<br />(example 26/04/1975)
</p>
</form>
</body>

Wednesday, April 20, 2011


<?php
//cookie headers must be sent before any other headers
//to unset all the session variables at once, use $_Sesson = array();
session_start();
$_SESSION['sess_var']="Hello World!";

echo 'The content of $_SESSION[\'sess_var\'] is ' . $_SESSION['sess_var'] . '<br/>';

?>
<a href="page2.php">Next page</a>;


Here is another tutorial from the book PHP and MySQL web development


<?php
session_start();
//the scripts activites revolve around the valid_user session variable. the baseic idea is that if someone logs in successfully, you will register a session variable
//called $_SESSION['valid_user']
if (isset($_POST['userid']) && isset($_POST['password']))
{
// if the user has just tried to log in
$userid = $_POST['userid'];
$password = $_POST['password'];

$db_conn = new mysqli('localhost', 'webauth', 'webauth', 'auth');

if (mysqli_connect_errno()) {
echo "Connection to database failed: " . mysqli_connect_error();
exit;
}

$query = "select * from authorized_users " . "where name='$userid' " . " and password='$password'";

$result = $db_conn->query($query);
if ($result->num_rows)
{
// if they are in the database register the user id
$_SESSION['valid_user'] = $userid;
}

$db_conn->close();

}
?>
<html>
<body>
<h1>Home Page</h1>
<?php
if (isset($_SESSION['valid_user']))
{
echo 'You are logged in as: ' . $_SESSION['valid_user'] . '<
';
echo '<a href="logout.php">Log Out</a><br />';
}
else
{
if (isset($userid))
{
// if they have tried and failed to log in
echo 'Could not log you in. <br />';
}
else
{
// they have not tried to log in yet or have logged out
echo 'You are not logged in.<br />';
}

//provide form to log in
echo '<form method="post" action="authmain.php">';
echo '<table>';
echo '<tr><td>Userid:</td>';
echo '<td><input type="text" name="userid"></td></tr>';
echo '<tr><td>Password:</td>';
echo '<td><input type="password" name="password"></td></tr>';
echo '<tr><td colspan="2" align="center">';
echo '<input type="submit" value="Log In"></td></tr>';
echo '</table></form>';

}
?>
<br />
<a href="members_only.php">Members section</a>
</body>


Here is the continuation of that tutorial on sessions and log ins


<?php

session_start();

echo '<h1>Members Only';

// check session variable

if (isset($_SESSION['valid_user']))
{
echo '<p>You are logged in as ' . $_SESSION['valid_user'] . ' </p>';
echo '<p>Members only content goes here</p>';
}
else
{
echo '<p>You are not logged in.</p>';
echo '<p>Only logged in members may see this page.</p>';
}
echo '<a href="authmain.php">Back to main page</a>';
?>


Here is the final page from that tutorial / project



<?php

session_start();

//store to test if they *were* logged in
$old_user = $_SESSION['valid_user'];
unset($_SESSION['valid_user']);
session_destroy();
?>
<<html>
<body>
<h1>Log Out</h1>
<?php
if (!empty($old_user))
{
echo 'Logged out.<br />';
}
else
{
//if they weren't logged in but came to this page somehow
echo 'You were not logged in, and so have not been logged out<br/>';
}
?>

<a href="authmain.php">Back to the Main Page</a>
</body>


Here is another tutorial on arrays


<?php
$customer = array('first' => 'Bill', 'last' => 'Jones', 'age' => '24', 'street' => '123 Main St.', 'city' => 'Pacifica', 'state' => 'California');
extract($customer);
print "<p>$first $last is $age years old, and lives in $city, $state</p>";

extract($customer, EXTR_PREFIX_ALL, 'cust');
print "<p>$cust_first $cust_last is $cust_age years old, and lives in $cust_city, $cust_state.</p>";
?>

Sunday, April 17, 2011

Sunday 4.17.11

Using UNSET


<?php
$dogs = array('Lassie' => 'Collie', 'Bud' => 'Sheepdog', 'Rin-Tin-Tin' => 'German Shepherd', 'Snoopy' => 'Beagle');
printf("
%s
\n", var_export($dogs, TRUE));

unset($dogs['Rin-Tin-Tin']);
printf("
%s
\n", var_export($dogs, TRUE));

?>


Here is another tutorial dealing with arrays


<?php
$languages = array('French', 'German', 'Russian', 'Chinese', 'Hindi', 'Quecha');
printf("

Original array:

%s
\n", var_export($languages, TRUE));

$removed = array_shift($languages);
printf("

Using array_shit():
Removed element: %s

%s
\n", $removed, var_export($languages, TRUE));
$removed = array_pop($languages);
printf("

Using array_pop():
Removed element: %s

%s
\n", $removed, var_export($languages, TRUE));
unset($languages[count($languages) - 1]);
printf("

Using unset() and count():

%s
\n", var_export($languages, TRUE));
?>

Friday, April 15, 2011

Friday, April 15th 2011


<?php
//create short variable names
$isbn=$_POST['isbn'];
$author=$_POST['author'];
$title=$_POST['title'];
$price=$_POST['price'];

if (!$isbn || !$author || !$title || !$price) {
echo "You have not entered all the required details.<br /> Please go back and try again.";
exit;
}

//I think that i have get magic quotes off.
if (!get_magic_quotes_gpc()) {
$isbn = addslashes($isbn);
$author = addslashes($author);
$title = addslashes($title);
$price = doubleval($price);
}

@ $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');

if (mysqli_connect_errno()){
echo "Error: Could not connect to database. Please try again later.";
exit;
}

$query = "insert into books values ('" . $isbn . "', '" . $author . "', '" . $title . "', '" . $price . "')";
$result = $db->query($query);

if ($result) {
echo $db->affected_rows . " book inserted into database . ";
} else {
echo "An error has occurred. The item was not added.";
}

$db->close();
?>




<?php
$dogs = array('Lassie' => 'Collie', 'Bud' => 'Sheepdog', 'Rin-Tin-Tin' => 'Alsatian');

$birds = array('parrot', 'magpie', 'lorikeet', 'cuckoo');

printf("

There are %d dogs and %d birds.

", count($dogs), count($birds));

$birds[] = 'ibis';
printf("<p>There are now %d birds:

", count($birds));
printf("<pre>%s</pre>\n", var_export($birds, TRUE));

$birds[10] = 'heron';
unset($birds[3]);
?>





<?php
$birds = array('parrot', 'magpie', 'lorikeet', 'cuckoo');
$more_birds = array_pad($birds, 6, 'some bird');

printf("<p>Birds:</p><pre>%s</pre>\n", var_export($birds, TRUE));
printf("<p>More birds:

%s</pre>\n", var_export($more_birds, TRUE));

?>


Here is another tutorial dealing with arrays



<?php
$birds = array('parrot', 'magpie', 'lorikeet', 'cuckoo');
$more_birds = array_pad($birds, 6, 'some bird');

printf("<p>Birds:</p><pre>%s</pre>\n", var_export($birds, TRUE));
printf("<p>More birds:</p>%s</pre>\n", var_export($more_birds, TRUE));

?>




<?php
$dogs = array('Lassie' => 'Collie', 'Bud' => 'Sheepdog', 'Rin-Tin-Tin' => 'Alsatian');

$pups = array_pad($dogs, 5, 'mutt');
printf("<p>Pups (left padding):</p><pre>%s</pre>\n", var_export($pups, TRUE));

$pups = array_pad($dogs, -5, 'mutt');
printf("<p>Pups (left padding):</p><pre>%s</pre>\n", var_export($pups, TRUE));

printf("<p>Dogs:</p><pre>%s</pre>\n", var_export($dogs, TRUE));

?>


Here is an example dealing with foreach looping


<?php
$dogs = array('Lassie' => 'Collie', 'Bud' => 'Sheepdog', 'Rin-Tin-Tin' => 'German Shepard', 'Snoopy' => 'Beagle');

foreach($dogs as $name => $breed)
print "$name is a $breed.<br/>\n";

$birds = array('parrot', 'magpie', 'lorikeet', 'cuckoo');

foreach($birds as $bird)
print "$bird";

print "<br/>";

$birds[] = 'ibis';
$birds[10] = 'heron';
unset($birds[3]);

foreach($birds as $bird)
print "$bird ";
?>

Monday, April 11, 2011


<?php
//create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'You have not entered search details. Please go back and try again.';
exit;
}

if (!get_magic_quotes_gpc()) {
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}

@ $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}

$query = "select * from books where ".$searchtype . " like '%" . $searchterm. "%'";
$result = $db->query($query);

$num_results = $result->num_rows;

echo "<P>Number of books found: " . $num_results . "</p>";

for ($i=0; $i < $num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>" . ($i+1) . " . Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br/>Price: ";
echo stripslashes($row['price']);
echo "</p>";
}

$result->free();
$db->close();

?>

Friday, April 8, 2011

Friday April 8 2011

//create array of product names
var productNames = [];
productNames[0] = "C64 Computer";
productNames[1] = "C64 Monitor";
productNames[2] = "C64 Disk Drive";
productNames[3] = "C64 Mouse";
productNames[4] = "C64 Printer";

var productPrices = [];
productPrices[0] = 719.99;
productPrices[1] = 429.99;
productPrices[2] = 299.99;
productPrices[3] = 49.99;
productPrices[4] = 349.99;

var checkCounter = 0;

var urlString = "?";


function activate(number) {
var name = "num" + number;
makeVisible(name, 1);
calculateTotal();
}

function makeVisible(name, number) {
//http://www.bennadel.com/blog/142-Ask-Ben-Javascript-String-Replace-Method.htm
checkCounter = checkCounter + 1;
var chkName = "check" + name.replace( "num", "" )
var chkBox = document.getElementById(chkName);
var target = document.getElementById(name);
target.className = "notInvisible";
if (number==1) {
target.value = 1;
}
// be sure to use == rather than = !!!!!!!!!!!!!!!!!!!!!!!!! spent twenty minutes on that
if (chkBox.checked == false) {
target.className = "invisble";
target.value = "";
}
}

// had to take this out of calculateTotal so I could reuse it on the next page
function displayTotalString(numTotal) {
var totalCost = document.getElementById("totalSpan");
countTotal = "$" + numTotal;
var totalCostText = document.createTextNode(countTotal);
//i should find a way to turn this into a function
if (totalCost.hasChildNodes()){
totalCost.removeChild(totalCost.lastChild);
}
totalCost.appendChild(totalCostText);
}

//calculate the total for display on the two pages
function calculateTotal(){
//check to see if anything has been selected, if so, enable the submit button
var enableButtonCounter = 0;
var numTotal = 0;
for (i=1; i<6; i++) {
var num = "num" + i;
var numField = document.getElementById(num).value;
if (numField > 0) {
enableButtonCounter += 1;
var price = productPrices[i-1];
numTotal += (numField * price);
}
displayTotalString(numTotal);
}

var subButton = document.getElementById("submitButton" );
if (enableButtonCounter > 0) {
subButton.disabled=false;
} else {
subButton.disabled=true;
}
} //end function calculate total

//create an object for items for sale
function item(id, cost) {

this.id = id;
this.divID = "div" + id;
this.cost = cost;
this.image = "images/product_" + id + ".jpg";


//diplay the product
this.display = function() {
var longName = productNames[this.id - 1];
this.createDiv();
this.createImage();
this.createText(longName);
//I was going to create a purchase button here but it dynamic event handlers are not really supported (whoops!) and window.event is not supported in Firefox, and that was my last option!
//if i could establish sessions / cookies I could get it to work
//this.createButton();
}

//note to self: only put parenthesis infront of the function keyword, not the this.createDIV part
this.createDiv = function() {
var productHolder = document.getElementById("products");
var divName = document.createElement("div");
var idID= this.divID;
divName.setAttribute('id', idID);
divName .className = "productDIV";
productHolder.appendChild(divName );
}


this.createImage = function() {
//http://www.hotscripts.com/forums/javascript/45658-solved-can-you-use-variable-getelementbyid.html
var divHolder = document.getElementById(this.divID);
var imageHolder = document.createElement("img");
//className assign class to the element
imageHolder.className = "productImage";
imageHolder.id = "id" + this.id;
imageHolder.src = this.image;
divHolder.appendChild(imageHolder);
}

this.createText = function(longName) {
var divHolder = document.getElementById(this.divID);
var newP = document.createElement("p");
var textName = document.createTextNode(longName);
var textCost = "$" + this.cost;
var textPrice = document.createTextNode(textCost);
var textBreak= document.createElement("br");
newP.appendChild(textName);
newP.appendChild(textBreak);
newP.appendChild(textPrice);
divHolder.appendChild(newP);
}



}

//productNames, productPrices
//get subtrings from query string
var basicString = "";
var arrayHolder = [];
var totalTotal = 0;

function getQueryString() {
//basicString = window.location.search.substring(1);
//alert(basicString);
basicString = window.location.search;
basicString = basicString.substring(1);
array1 = basicString.split("&");
for (i=0; iarray2 = array1[i].split("=");
if (!isNaN(array2[1])){
arrayHolder.push(array2[1]);
}

}

}

function displayResults(){
for (i=0; iif (arrayHolder[i] != 0) {
buildDisplay(productNames[i], productPrices[i], arrayHolder[i]);
var subTotal = productPrices[i] * arrayHolder[i];
totalTotal += subTotal;
}
}
displayTotalString(totalTotal);
}

function buildDisplay(name, price, quantity){
var targetDiv = document.getElementById('purchasedItems');
var targetP = document.createElement("p");
var blueSpan = document.createElement("span");
blueSpan.className = "blueSpan";
var emSpan = document.createElement("span");
emSpan.className="emphasize";
var dollarPrice = "$" + price;
var mQuantity = " (" + quantity +")" + " = ";
var lineTotal = price * quantity;
var displayLineTotal = "$" + lineTotal;
var nameNode = document.createTextNode(name);
var priceNode = document.createTextNode(dollarPrice);
var quantityNode = document.createTextNode(mQuantity);
var lineTotalNode = document.createTextNode(displayLineTotal);
blueSpan.appendChild(lineTotalNode);
emSpan.appendChild(nameNode);
targetP.appendChild(emSpan);
targetP.appendChild(priceNode);
targetP.appendChild(quantityNode);
targetP.appendChild(blueSpan);
targetDiv.appendChild(targetP);
}

//copy the billing info to shipping
function copyShipping() {
var chkBox = document.getElementById("shippingCheck");
//shipping addresses
var sAddress = document.getElementById("saddress");
var sCity = document.getElementById("scity");
var sState = document.getElementById("sstate");
var sZip = document.getElementById("szip");
if (chkBox.checked == true) {
var bAddress = document.getElementById("baddress");
var bCity = document.getElementById("bcity");
var bState = document.getElementById("bstate");
var bZip = document.getElementById("bzip");

sAddress.value = bAddress.value;
sCity.value = bCity.value;
sState.value = bState.value;
sZip.value = bZip.value;
} else {
sAddress.value = "";
sCity.value = "";
sState.value = "";
sZip.value = "";
}
}

Monday, April 4, 2011

Monday April 4th 2011


<script type="text/javascript">
//initialize theBeatles array and store in a variable
var theBeatles = new Array();
//set the values using keys rather than numbers
theBeatles["drummer"]= "Ringo";
theBeatles["RhythmGuitar"] = "John";
theBeatles["BassGuitar"] = "Paul";
theBeatles["LeadGuitar"] = "George";
var indexKey;
//write out each indexKey and the value for that indexKey from the array
for (indexKey in theBeatles) {
document.write("indexKey is " + indexKey + "<br>");
document.write("item value is " + theBeatles[indexKey] + "<br><br>");
}
</script>


here is another tutorial



<script type="text/javascript">
var userNumbers = new Array();
var userInput = 0;
var arrayIndex = 0;
var message = '';
var total = 0;
// loop for as long as the user doesn't input 99
while (userInput != 99) {
userInput = prompt("Enter a number, or 99 to exit", "99");
userNumbers[arrayIndex] = userInput;
arrayIndex++;
}

message += "You entered the following:\n";
for (var i = 0; i < arrayIndex-1; i++) {
message += userNumbers[i] + '\n';
total += Number(userNumbers[i]);
}
message += 'Total: ' + total + '\n';
alert(message);
</script>


Another one:


<script type="text/javascript">
var userNumbers = new Array();
var userInput;
var arrayIndex = 0;
do {
userInput = Number(prompt("Enter a number, or 99 to exit", "99"));
//check that user input is a valid number,
//and if not, break with error msg
if (isNaN(userInput)){
document.write("Invalid data entered: please enter a number between 0 and 99 in numerals");
break;
}
//If break has been activated, code will continue from here
userNumbers[arrayIndex] = userInput;
arrayIndex++;
} while (userInput != 99)
</script>


Here is a simple unobtrusive javascript form validation


<script type="text/javascript">
function checkSearch()
{
if(!document.getElementById || !document.createTextNode)
{
return;
}
if(!document.getElementById('search'))
{
return;
}

var searchValue=document.getElementById('search').value;
if(searchValue=='')
{
alert('Please enter a search term');
return false;
}
else
{
return true;
}
}
</script>