PHP - Adding Image By $id Tag
Hello,
I'm just learning PHP and I'm trying to have a different image display for each Item in a shop.. My only guess to how this would be possible is to name the IMG after the ID of the Item, like Item #10 has a name of 10.jpg. My question is, how would I go about doing this? or is there a better way of doing this.. Here is the Code I currently have. Thanks for help. Code: [Select] <?php session_start(); $page = 'index.php'; mysql_connect ('localhost','root','') or die(mysql_error()); mysql_select_db ('buggs') or die (mysql_error()); function products() { $get = mysql_query('SELECT id, name, description, price FROM products WHERE quantity > 0 ORDER BY id DESC LIMIT 10'); if (mysql_num_rows($get)==0) { echo "There are no products to display!"; } else { while ($get_row = mysql_fetch_assoc($get)) { echo '<p>'.$get_row['id'].'<br />'.$get_row['name'].'<br />'.$get_row['description'].'<br />'.number_format($get_row['price'], 2).' <a href="cart.php?add='.$get_row['id'].'">Add</a></p>'; } } } ?> and the code to where it displays.. Code: [Select] <?php require 'cart.php'; ?> <html> <head> </head> <body> <?php products();?> </body> </html> Similar TutorialsHi, I've read a lot of places that it's not recommended to store binary files in my db. So instead I'm supposed to upload the image to a directory, and store the link to that directory in database. First, how would I make a form that uploads the picture to the directory (And what kinda directories are we talking?). Secondly, how would I retrieve that link? And I guess I should rename the picture.. I'd appreciate any help, or a good tutorial (Haven't found any myself). So its a virtual pet script I'm making. This script changes the image of the pet with time. It also puts the user's name,in text on the image. For some reason It doesnt turn out too well= http://amiteka.comli.com/viewpet_forum.php?id=1 Can someone tell me what is wrong with the script or how I can make it show something like; Error on line # <?php require_once('./inc/config.php'); function greaterDate($dformat, $beginDate, $endDate) { $subtract = $endDate - $beginDate; if($subtract > 0) { return 1; } else { return 0; } } function check(){ $pid = mysql_real_escape_string($_GET['id']); $result = mysql_query("SELECT * FROM `pets_adopted` WHERE `id` = '{$pid}'"); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $results = mysql_query("SELECT * FROM `pets_list` WHERE `id` = '{$row [petid]}'"); $pet = mysql_fetch_array($results); $results2 = mysql_query("SELECT * FROM `users` WHERE `id` = '{$row [adopter]}'"); $usercc = mysql_fetch_array($results2); if(greaterDate(".", $row[fulldate], date('Ymd')) > 0) { $im = showpet_forum($pet[adulturl]); $image = imagecreatefrompng($im); return imagepng($image); header('Content-type: image/png'); } elseif(greaterDate(".", $row[halfdate], date('Ymd')) > 0 && greaterDate (".", $row[fulldate], date('Ymd')) <= 0){ $im = showpet_forum($pet[teenurl]); $image = imagecreatefrompng($im); return imagepng($image); header('Content-type: image/png'); } elseif(greaterDate(".", $row[halfdate], date('Ymd')) <= 0){ $im = showpet_forum($pet[babyurl]); $image = imagecreatefrompng($im); return imagepng($image); } } } echo check(); ?> Thank you for any help. Hiya all, Firstly thanks for the previous help with the arrays and that... you guys (or girls) ROCK ! But now I am stuck... lol. I am creating a simple motor dealer script for a friend with a garage and a few cars. The idea is... they fill in the form... upload the image(s) and then it adds it in to the database and displays the info on the page with other cars. So far I have got it to array all the info in the database how I want (thanks to you lot !). Now I need to add another box on the add vehicle page to upload photos and then on the show vehicles page I need it to show the uploaded photos next to the vehicles info. This is what I have so far: showvehicles.php: <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Current Showroom</B></CENTER> <BR> <!-- VIEWING BIT --> <?php include('dbconnect.php') ?> <?php // Make a MySQL Connection $query = "SELECT * FROM cars"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo "<TABLE CELLPADDING=0 CELLSPACING=0 WIDTH=100% BORDER=0>"; echo "<TR />"; echo "<TD WIDTH=30% VALIGN=TOP />"; echo " <IMG SRC=immg.gif /> "; echo "<br />"; echo "</TD>"; echo "<TD WIDTH=10 VALIGN=TOP />"; echo " "; echo "</TD>"; echo "<TD />"; echo "<font size=3 face=arial /><B >"; echo $row['CarPrice']; echo "</B><font size=2 face=arial />"; echo "<br />"; echo $row['CarTitle']; echo "<br />"; echo "Vehicle Type: "; echo $row['CarName']; echo "<br />"; echo "Vehicle Mileage: "; echo $row['CarMiles']; echo "<br />"; echo "Description: "; echo "<br />"; echo "<br />"; echo $row['CarDescription']; echo "<br />"; echo "</TD>"; echo "</TR>"; echo "</TABLE>"; echo "<hr WIDTH=100% COLOR=BLACK />"; } ?> <!-- END OF VIEWING BIT --> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> AddVehicle.php <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Add a Vehicle</B></CENTER> <BR> <form action="inserts.php" method="post"> <CENTER>Vehicle Name:</CENTER> <CENTER><input type="text" name="CarName"></CENTER> <br> <CENTER>Vehicle Type:</CENTER> <CENTER><input type="text" name="CarTitle"></CENTER> <br> <CENTER>Vehicle Price:</CENTER> <CENTER><input type="text" name="CarPrice"></CENTER> <br> <CENTER>Vehicle Mileage:</CENTER> <CENTER><input type="text" name="CarMiles"></CENTER> <br> <CENTER>Vehicle Description:</CENTER> <CENTER><textarea name="CarDescription" rows="10" cols="30"></textarea></CENTER> <br> <CENTER><input type="Submit"></CENTER> </form> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> inserts.php (Actually handles adding info to the database thats been typed in form) <HTML> <HEAD> <TITLE>Barry Ottley Motor Co - Quality Used Motors - Stanford-Le-Hope, Essex</TITLE> </HEAD> <BODY LINK="#000000" ALINK="#000000" VLINK="#000000"> <CENTER><IMG SRC="logo.jpg"></CENTER> <CENTER> <TABLE WIDTH="840" CELLPADDING="0" CELLSPACING="0" BORDER="0"> <TR> <TD WIDTH="186" valign="top"> <BR> <CENTER><A HREF="index.html"><IMG SRC="homepage.jpg" alt="Homepage" border="0"></A></CENTER> <CENTER><A HREF="showroom.php"><IMG SRC="showroom.jpg" alt="Our Online Showroom" border="0"></A></CENTER> <CENTER><A HREF="location.html"><IMG SRC="ourlocation.jpg" alt="Our location" border="0"></A></CENTER> <CENTER><A HREF="aboutus.html"><IMG SRC="aboutus.jpg" alt="About Us" border="0"></A></CENTER> <CENTER><A HREF="contactus.php"><IMG SRC="contactus.jpg" alt="Contact Us" border="0"></A></CENTER> </TD> <TD WIDTH="30" valign="top"> </TD> <TD valign="top"> <FONT SIZE="2" FACE="ARIAL"> <CENTER><B>Vehicle Added</B></CENTER> <BR> <?php mysql_connect("localhost", "wormste1_barry", "barry") or die(mysql_error()); mysql_select_db("wormste1_barry") or die(mysql_error()); $CarName = mysql_real_escape_string(trim($_POST['CarName'])); $CarTitle = mysql_real_escape_string(trim($_POST['CarTitle'])); $CarPrice = mysql_real_escape_string(trim($_POST['CarPrice'])); $CarMiles = mysql_real_escape_string(trim($_POST['CarMiles'])); $CarDescription = mysql_real_escape_string(trim($_POST['CarDescription'])); mysql_query("INSERT INTO cars (CarName, CarTitle, CarPrice, CarMiles, CarDescription) VALUES('$CarName', '$CarTitle', '$CarPrice', '$CarMiles', '$CarDescription' ) ") or die(mysql_error()); echo "The vehicle data has been added!"; ?> </TD> </TR> </TABLE> <BR><BR><BR><BR> <CENTER><FONT FACE="VERDANA" SIZE="1"> This website was designed and is hosted by <A HREF="http://www.IRCDirect.co.uk">IRC Direct Website Design™</A> 2010 </CENTER> <BR> <CENTER><A HREF="admin.php">Employee Area</A> </BODY> </HTML> If anyone can help me... much appreciated. I googled it and it started quoting BLOBS and stuff... i was confused Hi There, I want to add a picture to an existing user. The sql looks like: CREATE TABLE `klanten` ( `id` int(4) unsigned NOT NULL auto_increment, `username` varchar(32) NOT NULL, `password` varchar(32) NOT NULL, `level` int(4) default '1', `filename` varchar(255) not null, `mime_type` varchar(255) not null, `file_size` int not null, `file_data` mediumblob not null, primary key (id), index (filename) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci; id, username, password and level are allready filled in. Now i need some code to go with <form method="post" action="process.php" enctype="multipart/form-data"> <div> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </div> </form> process.php: <?php require_once 'database.php'; function assertValidUpload($code) { if ($code == UPLOAD_ERR_OK) { return; } switch ($code) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $msg = 'Image is too large'; break; case UPLOAD_ERR_PARTIAL: $msg = 'Image was only partially uploaded'; break; case UPLOAD_ERR_NO_FILE: $msg = 'No image was uploaded'; break; case UPLOAD_ERR_NO_TMP_DIR: $msg = 'Upload folder not found'; break; case UPLOAD_ERR_CANT_WRITE: $msg = 'Unable to write uploaded file'; break; case UPLOAD_ERR_EXTENSION: $msg = 'Upload failed due to extension'; break; default: $msg = 'Unknown error'; } throw new Exception($msg); } $errors = array(); try { if (!array_key_exists('image', $_FILES)) { throw new Exception('Image not found in uploaded data'); } $image = $_FILES['image']; // ensure the file was successfully uploaded assertValidUpload($image['error']); if (!is_uploaded_file($image['tmp_name'])) { throw new Exception('File is not an uploaded file'); } $info = getImageSize($image['tmp_name']); if (!$info) { throw new Exception('File is not an image'); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } if (count($errors) == 0) { // no errors, so insert the image $query = sprintf( "insert into klanten (filename, mime_type, file_size, file_data) values ('%s', '%s', %d, '%s')", mysql_real_escape_string($image['name']), mysql_real_escape_string($info['mime']), $image['size'], mysql_real_escape_string( file_get_contents($image['tmp_name']) ) ); mysql_query($query, $con); $id = (int) mysql_insert_id($con); // finally, redirect the user to view the new image header('Location: view.php?id=' . $id); exit; } ?> <html> <head> <title>Error</title> </head> <body> <div> <p> The following errors occurred: </p> <ul> <?php foreach ($errors as $error) { ?> <li> <?php echo htmlSpecialChars($error) ?> </li> <?php } ?> </ul> <p> <a href="upload.php">Try again</a> </p> </div> </body> </html> to add to an existing user. Can somebody help me here? Best regards, Martijn Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> This might be more of a mySQL question or a PHP question, I'm not exactly sure. I have a field in my table (Deals) called "Price". All I want is the sum of that field. I tried using something like: $price += $row['Price']; This ended up as one long string, even though the database is set as a decimal number field. Then I tried doing it from mySQL like this (from what I read), but I don't think I have the full answer: foreach($stmt->query('SELECT SUM(Price) FROM Deals') as $row) { echo "<tr>"; echo "<td>Total</td>"; echo "<td> ->".$row['SUM(Price)']."</td>"; echo "</tr>"; } Anyway, if someone could just show me how to get that sum, I would greatly appreciate it because I am missing something here. Hi can someone please show me how I should include a Code: [Select] <div id="css"></div> in this line Code: [Select] echo $AB_LANGS['CalendarInstructions']; I have tried several attempts with no joy. Many thanks hi i been working on this code witch will add what ever text i want to my database all is working great but what i am having problems with is inserting a url in the same field as vidID it will look like this in the database hxxp://xxx.mysitehere.com/index.php?vid=vidID hope you guys know what im talking about im having a hard time explaining it sorry. Code: [Select] <?php $host="xxxxx"; $username="xxxxxxx"; $password="xxxxxxx"; $db_name="xxxxxxx"; $tbl_name="xxxxxxx"; $message = strtoupper(trim($_REQUEST['message'])); $sender = strtoupper(trim($_REQUEST['sender'])); $email = strtolower(trim($_REQUEST['email'])); $vidID =$_REQUEST['vidID']; mysql_connect("$host", "$username", "$password")or die("cannot connect server "); mysql_select_db("$db_name")or die("cannot select DB"); $sql="INSERT INTO $tbl_name(message,sender,email,vidID)VALUES('$message','$sender', '$email', '$vidID')"; $result=mysql_query($sql); ?> I just want some advice and need to know if I can do the following the script which displays partially like this Code: [Select] function getMainLogo() { global $dir, $site; $sFileName = getParam('sys_main_logo'); if(!file_exists($dir['mediaImages'] . $sFileName)) return ''; return '<a href="' . BX_DOL_URL_ROOT . '"><img src="' . $site['mediaImages'] . $sFileName . '" class="mainLogo" alt="logo" /></a>'; } function getPromoImagesArray() { global $dir; Can I add the javascript so its like this? Code: [Select] function getMainLogo() { global $dir, $site; echo ' < script type="text/javascript > banners = new Array(); banners[0] = "www.weareapackage.com,weareapackage.com/images/WePackageBanner.gif,Dating for Single Parents,468,60"; banners[1] = "www.friendsordating.com,www.friendsordating.com/images/bannersketch (2).png,Free Dating for Singles,468,60"; banners[2] = "www.lovelooker.com,parentmeets.com/images/LoveLooker.gif,Adult Dating,468,60"; rand = Math.floor(Math.random() * banners.length); b = banners[rand].split(","); url = b[0]; img = b[1]; des = b[2]; wid = b[3]; hei = b[4]; document.write('<a href="' + url + '" target="_blank"><img src="' + img + '" width="'+ wid +'" height="'+ hei +'" border="0" alt="' + des + '" /></a>'); < /script type="text/javascript > ;' } $sFileName = getParam('sys_main_logo'); if(!file_exists($dir['mediaImages'] . $sFileName)) return ''; return '<a href="' . BX_DOL_URL_ROOT . '"><img src="' . $site['mediaImages'] . $sFileName . '" class="mainLogo" alt="logo" /></a>'; } function getPromoImagesArray() { global $dir; Im not familiar with adding the javascript to the middle of the code, I am not asking for a debugger I am just asking for friendly advice, I am very new to this and dont completely understand, thank you. what is the propper way to write Code: [Select] $payrollweek="10"; date('Y-m-d', strtotime("+($payrollweek - 2) week $payrollend") ), "<br />"; its the ("+($payrollweek - 2) that isnt working i think Hello.
I have a sports league and the captain's page has a menu bar allowing links to sub pages. I would like to only add the URL part if a condition is met. In my database I have a league field called "session" for Spring or Summer sessions.
The menu bar has 5 simple columns for hyperlinks:
Home | Edit Team | Add Player | Edit My Information | Log Out |
What I would like to do is to only display say the "Edit Team" with hyperlink if the league session = "Summer" (that was Spring teams cannot edit their information at this point in time). I am trying to create an IF-Else statement, but can't quite get it right. I am a novice PHP coder, so I could really use some help. Here is the current code for this short section:
<table width="800" border="0" cellpadding="0" cellspacing="0"> <tr> <td><img src="images/BBV_CP_top.jpg" width="800" height="200"></td> </tr> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="2"> <tr> <td width="6%" class="menu"><a href="home.php"> Home</a> </td> <td width="9%" class="menu">Edit Team </a></td> <td width="12%" class="menu">Add Player</td> <td width="63%" class="menu">Edit My Information</a> </td> <td width="10%" class="menu"><a href="logout.php">Log Out </a></td> </tr> </table>How can I create "Edit Team" to be a hyperlink ONLY IF the condition (league = Summer) is TRUE? $team is the query that returns the league results from the MSSQL query. Thanks in advance for your help. Hi ! please help me . im having a trouble with this im actually new to php. I had this working before, but my coding structure has changed a bit and need help with syntax. My function I have down ok. function cssfrommvp($mvp) { $class = array('MVP' => 'MVP'); return $class[$mvp]; } this is how I would add the class to a <td> with $row. Code: [Select] echo "<td class=\"".cssfrommvp($row['mvp'])."\">".$row['mvp']."</td>\n"; now using $array <td> . $MVP .</td>\n</tr> how would I do the same thing as done before with $row? I have seen somewhere that you can add to a string like so $var = "text"; or $string ="var"; &$var = "text"; it is the latter that I am wanting to know more about. When I try to add 30 days: Code: [Select] $date = date("Y-m-d"); $date = strtotime(date("Y-m-d", strtotime($date)) . " +30 days"); echo $date; and I echo date I get 1330664400 How do I get it to echo out 3/1/2012? I know the answer lies in the strtotime but I can't figure it out. I know it's a simple problem for most of you... Here's the code: Code: [Select] $year_values = array('Any', 'N/A', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012'); $db_year = explode(', ', $row['YEAR']); foreach($year_values as $year_value) { $selected_year = null; $year_label = $year_value; if(in_array($year_value, $db_year)) { $selected_year = ' checked="checked"'; $year_label = "<b>$year_value</b>"; } echo '<input type="checkbox" name="year" value="' . $year_value . '"' . $selected_year . ' />' . $year_label . ' '; } ?> [/code That pulls the data of the database and puts it in check boxes. The user can check/uncheck certain boxes but the problem is when it goes to the verify page it has only one value from the array that was selected. On the verify page it just checks if a box was checked and then implodes the array before submitting it into the database. [code] $year_s=implode($year,", "); So like I said there is only one value from the array when there should be as many as the user checks. So basically I believe the value isn't added to the array. hello, i have created a table that desplays perticulars, price per person and number of people. the fees is then calculated by multiplying price per person with number of people. till now everything is good. but the problem is when i try to calculate the total fees. here is an example to explain you better: Perticulars Price Per Person Number of people Amount something 10 100 1000 something else 20 100 2000 Total 3000 Code: [Select] $pert_query = mysql_query ("SELECT * FROM `perticulars` WHERE `invoice` =$invoice") or die(mysql_error()); $i = 1; $sum = 0 + $_SESSION['sum']; while($perticulars = mysql_fetch_array($pert_query, MYSQL_ASSOC)) { ?> <tr> <td style="border-collapse: collapse"><div align="center"><?php echo $i; $i++; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['perticulars']; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['ppc']; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['nop']; ?></div></td> <td style="border-collapse: collapse"><div align="center"> <?php $amount = $perticulars['ppc'] * $perticulars['nop']; echo $amount; $_SESSION['sum'] = $sum+$amount;?> </div></td> </tr><?php } ?> <tr> <td colspan="4" style="border-collapse: collapse"><div align="center">Total</div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $sum; ?></div></td> </tr> </table> From the above code you can see that i am getting the amount form $amount = $perticulars['ppc'] * $perticulars['nop']; by this each row has its own amount which i got by multiplying the data from mysql. the problem is how do i find out the Total. i know i am suppose to add up $amount but how? i even tired using sessions to store the amount and add the new amount to get total but the problem in using sessions is it messes up my next page, no using session is a very bad idea. Is it possible to add onto the value of a $_SESSION, rather replacing it? $_SESSION['order']['cartcontenttext'] += echo 'Small: "'.$content['sizes'].'"'; $_SESSION['order']['cartcontenttext'] += echo 'Medium: "'.$content['sizem'].'"'; $_SESSION['order']['cartcontenttext'] += echo 'Large: "'.$content['sizel'].'"'; ... so the result would be something like this: echo $_SESSION['order']['cartcontenttext']; Quote Small: 1Medium: 3Large: 2 I'm trying to get code to work along the following logic (or something similar if this logic isn't PHP-friendly). If a user inputs a URL with the http, I want the url left alone. If the user inputs the URL starting with www, I want http:// added to the beginning. If the user does anything else (in other words uses a relative link), I want the beginning of my url to be added on (because then I later check for it to open the website in a new window or not). Code: [Select] if (strpos($url, "http") == 0) { $url = $url; } else if (strpos($url, "www") == 0) { $url = "http://".$url; } else { $url = "http://www.mywebsite.com/".$url; }; Any suggestions? Hello everyone, I'm making a site with PHP script and PHPmyadmin database, i need some help with how to add news and then edit them or delete them on the site, not in the Database(if that is even possible to do it there), so far i can only delete the news, but when i try to add new stuff i just get the error message of my code, which is not very nice of it but hey, i'm a noob at this PHP so i must be doing something wrong. this is the code i have for the current situation. Code: [Select] <?php include_once( 'database_functions.php' ); $connectID = connectToDatabase( 'login' ); mysql_set_charset( 'utf8', $connectID ); $categories = mysql_query('SELECT * FROM ref_categories', $connectID); if( @$_POST && @$_POST['submitted'] && ( !@$_GET[ 'id' ] ) ) { $title = ( $_POST[ 'topic_name' ] ); $topic = ( $_POST[ 'topic_desc' ] ); //write to database mysql_query ( "INSERT into news (title, topic) VALUES ('$title', '$topic')", $connectID ) or die ("Unable to insert record into database"); print "Record successfully added"; } elseif( !$_POST && $_GET && $_GET['id'] ) { $id = $_GET['id']; $thisRecord = mysql_query("SELECT * FROM ref_categories WHERE id = $id", $connectID ) or die( "Can't Read this record." ); $recordData = mysql_fetch_array( $thisRecord, MYSQL_ASSOC ); } elseif( $_POST && $_POST['submitted'] && ( $_GET['id'] ) ) { $title = ( $_POST[ 'title' ] ); $topic = ( $_POST[ 'topic_desc' ] ); $id = $_GET['id']; $success = mysql_query( "SELECT * FROM news", $connectID ) or die( "Can't Update this record" ); if( $success ) { header( 'Location: links_admin.php?updated=1' ); } } else { } ?> |