PHP - Need Help With A Php Script For A Guestbook
Okay I am extremely new to PHP and am trying to make a 2 page guestbook, where one page has the form to submit a message to the guestbook and the other page displays the messages. However I am having some errors, one being that when I submit a test message it still shows the "please enter your name and comments" thing I have set when people don't fill the required fields. The other error I'm having is if I put two test messages into the guestbook some of the info from the last message fills in the fields of the other one instead of what was actually filled into the form.
For example, if I insert the name "Pat" and the comment "testing 1 2 3" into one message and than insert the name "Bob" and the comment "hi" for another message when I submit the second message it may instead of putting "hi" it'll put "testing 1 2 3" so I get: Posted by: Pat testing 1 2 3 ________________ Posted by: Bob testing 1 2 3 instead of: Posted by: Pat testing 1 2 3 ________________ Posted by: Bob hi Like it should.... What am I doing wrong???? My PHP code for submition is: Code: [Select] <?php //connecting to the Database $connect = mysql_connect("127.0.0.1","patben_guestbook","") or die("Error"); //selecting the table mysql_select_db("patben_guestbookdatabase") or die("Error"); //selecting ALL data $queryget = mysql_query("SELECT * FROM guestbook") or die("Error"); //sort the data while ($row = mysql_fetch_assoc($queryget)) { $id = $row['id']; $date = $row['date']; $name = $row['name']; $email = $row['email']; $song = $row['song']; $part = $row['part']; $comments = $row['comments']; //processing data echo " <table> <tr> <td> <b>Posted by:</b> $name ($email)<br /> <b>$date</b><br /> <b>Favorite Pat Song:</b> $song<br /> <b>Favorite Part of the Site:</b> $part </td> </tr> <tr> <td> ".nl2br(strip_tags($comments))." <hr /> </td> </tr> </table> "; } if ($_POST['submit']); { $date = date("Y-m-d"); $name = $_POST['name']; $comments = $_POST['comments']; if ($name&&$comments) { $queryget = mysql_query("INSERT INTO guestbook (id,date, name, email, song, part, comments) VALUES ('','$date','$name','$email','$song','$part','$comments')"); echo "Please wait... <meta http-equiv='refresh' content='2'>"; echo mysql_error(); } else echo "Please enter your name and comments"; } ?> And my HTML form is: Code: [Select] <form action="process.php" method="post"> <table width="500" border="0" cellspacing="2" cellpadding="0"> <tr valign="top"> <td width="500px" class="name"><span style="color:#ff0000"><b>*</b></span>Name:</td> <td width="500px"><input name="name" type="text" id="name" size="32" /></td> </tr> <tr valign="top"> <td width="500px" class="bodytext"> Email Address:</td> <td width="500px"><input name="email" type="text" id="email" size="32" /></td> </tr> <tr valign="top"> <td width="500px" class="pat"> Your Favorite Pat Song?:</td> <td width="500px"><input name="song" type="text" id="song" size="32" /></td> </tr> <tr valign="top"> <td width="500px" class="part"> Your Favorite Part of my Site?:</td> <td width="500px"><input name="part" type="text" id="part" size="32" /></td> </tr> <tr valign="top"> <td width="500px" class="comments"><span style="color:#ff0000"><b>*</b></span> Comment:</td> <td width="500px"><textarea name="comments" id="comments" cols="28" rows="6" class="comments"></textarea></td> </tr> <tr valign="top"> <td class="bodytext"> </td> <td align="left" valign="top"><input type="submit" name="Submit" value="Post" class="btn" /></td> </tr> </table> </form> Similar TutorialsI'm saving customer comments in an MYSQL. But the when I use mysql_real_escape_string() to filter the input data it's causing wired signs when it's displayed in the guest book. (E.g. whenever there is a ' sign, the output is \'). Is it safe to have a guest book without mysql_real_escape_string( or please suggest how should I go about creating this guest book on my website. Thanks. Bickey. I am trying to modify Guestbook. In order to access the page, the user must log in using a screen name and email address that has been registered with the website. What I want to take the log in information and automatically populate the Name and email field of the input comment form. I have set up SESSION Variables (see below for the login php). <?php session_start(); require_once("dbcon.php"); $form = "<table> <form action='login.php' method='post'> <tr> <td>Username: </td><td><input type='text' name='user' size='20' /> </tr> <tr> <td>Email: </td><td><input type='text' name='emad' size='30' /> </tr> <tr> <td><input type='submit' name='submit' value='Login' /> <td><a href='New Contact.html'>New Account </a> </tr> </form> </table>"; // Do NOT use \" when you still have the option to use singlequotes, looks so messy... $user = $_POST['user']; $emad = $_POST['emad']; //defining these in the start makes the source looks nicer if(!$_POST['submit']) die($form); // just kill the rest of the script if the form isn't submitted. if(!$user || !$emad) die("Required fields missing<br /><br /> $form"); // killing the rest of the script and echoing the form and error $sql = "SELECT ident FROM Mix WHERE password = '$pass' AND username = '$user'"; // just like with the variables and prints/echoes, you don't need to ".$var." anything with double quotemarks $res = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($res) > 0) { $row = mysql_fetch_assoc($res); $_SESSION['uid'] = $row['id']; $_SESSION['un'] = $_POST['user']; //Setup user name into session variable. $_SESSION['ua'] = $_POST['emad']; //Setup email address into session variable. echo "You have been logged in as $user at $emad. Click <a href=\"gbook.php\">here</a> to the member page."; } else { echo "That username/password combination doesn't exist!<br /><br/> $form"; } ?> Below is a copy of the Sign Form. php. I am trying to populate teh Name and email fields but the SESSION variables don't show up. Can someone figure out what I AM DOING WRONG. <?php session_start (); $un = $_SESSION['un']; $ua = $_SESSION['ua']; ?> <div id="gbook_guestbook" align="center"> <span class="gbook_guestbook"><?php echo $lang['t48']; ?></span><br class="clear" /> <span class="gbook_required"><?php echo $lang['t49']; ?></span> </div> <form action="gbook.php" method="post"> <!--SIGN FORM --> <div id="gbook_entries"> <?php if ($error) { echo '<div class="gbook_sign_error">'.$error.'</div>'; } ?> <div class="gbook_left"><span class="gbook_entries"><b><?php echo $lang['t50']; ?></b></span></div> <div class="gbook_right"><input type="hidden" name="<?php echo $myfield['name']; ?>" value="<?php echo $un; ?>" /></div> <?php echo $un; ?> <div class="clear"></div> <div class="gbook_left"><span class="gbook_entries"><?php echo $lang['t51']; ?></span></div> <div class="gbook_right"><input type="text" name="from" value="<?php echo $from; ?>" size="45" /></div> <div class="clear"></div> <?php if ($settings['use_url']) { ?> <div class="gbook_left"><span class="gbook_entries"><?php echo $lang['t53']; ?></span></div> <div class="gbook_right"><input type="text" name="url" value="<?php echo $url; ?>" size="45" maxlength="80" /></div> <div class="clear"></div> <?php } ?> <div class="gbook_left"><span class="gbook_entries"><?php echo $lang['t52']; ?></span></div> <div class="gbook_right"><input type="hidden" name="email" value="<?php echo $ua; ?>" /> <?php echo $ua; ?> <?php if ($settings['hide_emails']) { ?> <br class="clear" /><span class="gbook_entries"><i><?php echo $lang['t66']; ?></i></span> <?php } ?> </div> <div class="clear"></div> <div class="gbook_left"><span class="gbook_entries"><b><?php echo $lang['t16']; ?></b></span></div> <div class="gbook_right"><span class="gbook_entries"><i><?php echo $lang['t54']; ?></i></span></div> <textarea name="<?php echo $myfield['cmnt']; ?>" rows="12" cols="57" id="cmnt"><?php echo $comments; ?></textarea> <!--BOTTOM IMAGES --> <div id="gbook_bottom_images" class="gbook_bottom_images"> <a href="#" onclick="document.getElementById('cmnt').value += ' ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/bigsmile.gif" alt="" title="" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' :!cool: ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/cool.gif" alt=":!cool:" title=":!cool:" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' :!cry: ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/crying.gif" alt=":!cry:" title=":!cry:" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' :!devil: ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/devil.gif" alt=":!devil:" title=":!devil:" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/smile.gif" alt="" title="" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' :!mad: ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/mad.gif" alt=":!mad:" title=":!mad:" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' :!thinking: ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/thinking.gif" alt=":!thinking:" title=":!thinking:" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' :p ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/tongueout.gif" alt=":p" title=":p" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/wink.gif" alt="" title="" width="19" height="19" /></a> <a href="#" onclick="document.getElementById('cmnt').value += ' ';return false;"><img src="<?php echo $settings['tpl_path']; ?>images/emoticons/blush.gif" alt="" title="" width="19" height="19" /></a> <a href="javascript:openSmiley()" class="gbook_submitted"><?php echo $lang['t26']; ?></a><br /> <label><input type="checkbox" name="nosmileys" value="Y" class="gbook_checkbox" <?php echo $nosmileys; ?> /><span class="gbook_entries"><?php echo $lang['t28']; ?></span></label><br class="clear" /> <?php /* Private mesasges */ if ($settings['use_private']) { ?> <label><input type="checkbox" name="private" value="Y" class="gbook_checkbox" <?php echo $isprivate; ?> /><span class="gbook_entries"><?php echo $lang['t55']; ?></span></label><br class="clear" /> <?php } /* Print anti-SPAM features */ echo $settings['antispam']; ?> </div> <!--BOTTOM IMAGES END --> <div align="center"> <div class="clear"> </div> <!--SPAM TRAPS --> <!-- DON'T DELETE THESE HIDDEN FIELDS AND COMMENTS, THEY HELP CATCH STUPID SPAMBOTS! --> <input type="hidden" name="name" /> <input type="hidden" name="<?php echo $myfield['bait']; ?>" /> <!-- > <input type="text" name="comments" value="1" /> < --> <!--SPAM TRAPS END--> <input type="hidden" name="a" value="add" /> <input type="submit" value="<?php echo $lang['t88']; ?>" class="submit" /> </div> <p> </p> </div> <!--SIGN FORM END --> </form> I've found an example of guestbook that I would like to use on my site, but when I tested it I got the following error: Warning: fread() [function.fread]: Length parameter must be greater than 0 in C:\xampp\htdocs\xampp\index.php on line 66 I've included the bits of code for addguestbook.php guestbook.txt(didnt not include) and index.php. Also, is there a way that I could allow the client to look through out entries? I know very little about php, so any help is much appreciated. Code: [Select] ------ addguestbook.php code ------ <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css"> <!-- body,td,th { font-size: 12px; color: #000000; } a:link { text-decoration: none; color: #0066FF; } a:visited { text-decoration: none; color: #0066FF; } a:hover { text-decoration: underline; color: #0066FF; } a:active { text-decoration: none; } body { background-color: #CCCCCC; SCROLLBAR-FACE-COLOR: #0066FF; MARGIN: 0px; SCROLLBAR-HIGHLIGHT-COLOR: #0066FF; SCROLLBAR-SHADOW-COLOR: #0066FF; SCROLLBAR-3DLIGHT-COLOR: #0066FF; SCROLLBAR-ARROW-COLOR: #51B0F2; SCROLLBAR-TRACK-COLOR: #51B0F2; Courier New; SCROLLBAR-DARKSHADOW-COLOR: #000000 } --> </style> </HEAD> <BODY> <?php $file = "guestbook.txt"; $name = $_POST['name']; $email = $_POST['email']; $site = $_POST['site']; $msg = $_POST['msg']; $site = stripslashes($site); $msg = stripslashes($msg); $email = stripslashes($email); $name = stripslashes($name); $msg = str_replace ("<","<",$msg); $msg = str_replace ("\n","<br>",$msg); $site = str_replace ("<","<",$site); $site = str_replace ("\n","<br>",$site); $email = str_replace ("<","<",$email); $email = str_replace ("\n","<br>",$email); $name = str_replace ("<","<",$name); $name = str_replace ("\n","<br>",$name); if(empty($email) || empty($name) || empty($msg)) { echo "<h3>Sorry all fields are required</h3>"; } else { $fp = fopen($file,"a"); fwrite($fp, ' <font size="3"> <BR><BR> Name: '.$name.'<BR> Email: <a href="mailto:'.$email.'">'.$email.'</a><BR> Home Page: <a href="'.$site.'">'.$site.'</a><BR>Message: '.$msg.'<BR> '); fclose($fp); echo '<font size="3"><p align="center">Thank you '.$name.' for singing my guestbook</p></font>'; } ?> <div align="center"></div> <div align="center"></div> <div align="center"></div> <div align="center"></div> <p align="center"><a href="YOU`R INDEX.PHP LINK HERE">Back to GuestBook</a></p> <div align="center"></div> </BODY> </HTML> ---- finish ----- ---- index.php code ----- <HTML> <HEAD> <style type="text/css"> <!-- .style1 {font-size: 12px} body,td,th { font-size: 14px; } a { font-size: 12px; } body { background-color: #CCCCCC; SCROLLBAR-FACE-COLOR: #0066FF; MARGIN: 0px; SCROLLBAR-HIGHLIGHT-COLOR: #0066FF; SCROLLBAR-SHADOW-COLOR: #0066FF; SCROLLBAR-3DLIGHT-COLOR: #0066FF; SCROLLBAR-ARROW-COLOR: #51B0F2; SCROLLBAR-TRACK-COLOR: #51B0F2; Courier New; SCROLLBAR-DARKSHADOW-COLOR: #000000 } a:link { color: #0066FF; text-decoration: none; } a:visited { text-decoration: none; color: #0066FF; } a:hover { text-decoration: underline; color: #0066FF; } a:active { text-decoration: none; } --> </style> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><BODY> <form method="post" action="addguestbook.php"> <div align="center"></div> <div align="center"></div> <div align="center" class="style1"></div> <div align="center"><span class="style1">Name:</span><br /> <input name="name" type="text" size="30" maxlength="40" /> <br /> <span class="style1"><br /> Email:</span><br /> <input name="email" type="text" size="30" maxlength="40" /> <br /> <br /> <span class="style1">Home Page:</span><br /> <input name="site" type="text" size="30" value="http://" maxlength="40" /> <br /> <br /> <span class="style1">Message:</span><br /> <textarea name="msg" cols="22" rows="6"></textarea> <br /> <br /> <input type="reset" value="Reset" /> <input type="submit" value="Send" /> </div> <div align="center"> <p> </p> <?php $file = "guestbook.txt"; if (fopen($file, "r")) { $fil = "guestbook.txt"; $fo = fopen ($fil, "r"); $con = fread ($fo,filesize ($fil)); fclose ($fo); echo "$con"; } else { echo "<h3>Sorry there was an error please contact us now<h3>"; } ?></div> </BODY> </HTML> ---- finish ----- Hi All, Hope you can help. I am doing a very basic guestbook. Having problems with the posting method. The code is below all I am doing is insert a record into a mysql table but when I post getting a blank page with no obvious errors! code is below. if ($_POST['submit']) { $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $date = $_POST("Y-m-d"); $time = $_POST("H:i:s"); if($name&&$email&&$message) { $querypost = mysql_query("INSERT INTO guestbook (id, name, email, message, date, time) VALUES ('','$name','$email','$message','$date','$time')"); echo "Please wait.... <meta http-equiv='refresh' content='2'>"; } else echo "Please fill out all fields."; } I have a guestbook that writes an entry to a text file, but when I first run it I get this error: Warning: fread() [function.fread]: Length parameter must be greater than 0 in C:\xampp\htdocs\xampp\index.php on line 66 Is there a way I can get rid of that error and still be able to use my guestbook until I actual update my guestbook using a database? Hello! I am trying to make a Guestbook with help from the internet. I have created all sites what i need, but i have some problems with the Input. For example here is the Name inputfrom the "sign.php" <form id="form1" name="form1" method="post" action="addguestbook.php"> <td> <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td width="117">Name</td> <td width="14">:</td> <td width="357"><input name="name" type="text" id="name" size="40" /></td> </tr> And here is the "insert sequence" from the "guestbook.php": $sql="INSERT INTO $tbl_name(name, email, comment, datetime) VALUES('$name', '$email', '$comment', '$datetime')"; $result=mysql_query($sql); If i open the guestbook.php i just can see the datetime. What went wrong? Thanks, Mark p.S.: sorry for my english. I have a working guestbook, but adjusting the time is whats getting me. I am trying to get the time to change depending on the timezone. And I also trying to get the time in the format 1:00 PM, not 21:00. Then on a different note, how can I stop spamming and injections. Index page for guestbook Code: [Select] <HTML> <HEAD> <style type="text/css"> <!-- .style1 {font-size: 12px} body,td,th { font-size: 14px; } a { font-size: 12px; } body { background-color: #CCCCCC; SCROLLBAR-FACE-COLOR: #0066FF; MARGIN: 0px; SCROLLBAR-HIGHLIGHT-COLOR: #0066FF; SCROLLBAR-SHADOW-COLOR: #0066FF; SCROLLBAR-3DLIGHT-COLOR: #0066FF; SCROLLBAR-ARROW-COLOR: #51B0F2; SCROLLBAR-TRACK-COLOR: #51B0F2; Courier New; SCROLLBAR-DARKSHADOW-COLOR: #000000 } a:link { color: #0066FF; text-decoration: none; } a:visited { text-decoration: none; color: #0066FF; } a:hover { text-decoration: underline; color: #0066FF; } a:active { text-decoration: none; } --> </style> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><BODY> <form method="post" action="addguestbook.php"> <div align="center"></div> <div align="center"></div> <div align="center" class="style1"></div> <div align="center"><span class="style1">Name:</span><br /> <input name="name" type="text" size="30" maxlength="40" /> <br /> <span class="style1"><br /> Email:</span><br /> <input name="email" type="text" size="30" maxlength="40" /> <br /> <br /> <span class="style1">Home Page:</span><br /> <input name="site" type="text" size="30" value="http://" maxlength="40" /> <br /> <br /> <span class="style1">Message:</span><br /> <textarea name="msg" cols="22" rows="6"></textarea> <br /> <br /> <input type="reset" value="Reset" /> <input type="submit" value="Send" /> </div> <div align="center"> <p> </p> <?php $file = "guestbook.txt"; if (fopen($file, "r")) { $fil = "guestbook.txt"; $fo = fopen ($fil, "r"); $con = fread ($fo,filesize ($fil)); fclose ($fo); echo "$con"; } else { echo "<h3>Sorry there was an error please contact us now<h3>"; } ?></div> </BODY> </HTML> addguestbook.php Code: [Select] <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><style type="text/css"> <!-- body,td,th { font-size: 12px; color: #000000; } a:link { text-decoration: none; color: #0066FF; } a:visited { text-decoration: none; color: #0066FF; } a:hover { text-decoration: underline; color: #0066FF; } a:active { text-decoration: none; } body { background-color: #CCCCCC; SCROLLBAR-FACE-COLOR: #0066FF; MARGIN: 0px; SCROLLBAR-HIGHLIGHT-COLOR: #0066FF; SCROLLBAR-SHADOW-COLOR: #0066FF; SCROLLBAR-3DLIGHT-COLOR: #0066FF; SCROLLBAR-ARROW-COLOR: #51B0F2; SCROLLBAR-TRACK-COLOR: #51B0F2; Courier New; SCROLLBAR-DARKSHADOW-COLOR: #000000 } --> </style> </HEAD> <BODY> <?php function is_leapyear($year = 2004) { return ($year%4)==0; } $file = "guestbook.txt"; $name = $_POST['name']; $email = $_POST['email']; $site = $_POST['site']; $msg = $_POST['msg']; $site = stripslashes($site); $msg = stripslashes($msg); $email = stripslashes($email); $name = stripslashes($name); $msg = str_replace ("<","<",$msg); $msg = str_replace ("\n","<br>",$msg); $site = str_replace ("<","<",$site); $site = str_replace ("\n","<br>",$site); $email = str_replace ("<","<",$email); $email = str_replace ("\n","<br>",$email); $name = str_replace ("<","<",$name); $name = str_replace ("\n","<br>",$name); if(empty($email) || empty($name) || empty($msg)) { echo "<h3>Sorry all fields are required</h3>"; } else { $fp = fopen($file,"a"); $timestamp=date("M/D/Y h:m:s"); fwrite($fp, ' <font size="3"> <BR><BR> Posted: '.$timestamp.'<br /> Name: '.$name.'<BR> Email: <a href="mailto:'.$email.'">'.$email.'</a><BR> Home Page: <a href="'.$site.'">'.$site.'</a><BR>Message: '.$msg.'<BR> '); fclose($fp); echo '<font size="3"><p align="center">Thank you '.$name.' for singing my guestbook</p></font>'; } ?> <div align="center"></div> <div align="center"></div> <div align="center"></div> <div align="center"></div> <p align="center"><a href="index.php">Back to GuestBook</a></p> <div align="center"></div> </BODY> </HTML> I try to adjust my date and time to ("M-d-Y h:i:s A"), but when I do, I get 0's for the both the date and time. Code: [Select] <table width="400" border="0" align="center" cellpadding="3" cellspacing="0"> <tr> <td><strong>Test Sign Guestbook </strong></td> </tr> </table> <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form id="form1" name="form1" method="post" action="addguestbook.php"> <td> <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td width="117">Name</td> <td width="14">:</td> <td width="357"><input name="name" type="text" id="name" size="40" /></td> </tr> <tr> <td>Email</td> <td>:</td> <td><input name="email" type="text" id="email" size="40" /></td> </tr> <tr> <td valign="top">Comment</td> <td valign="top">:</td> <td><textarea name="comment" cols="40" rows="3" id="comment"></textarea></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Submit" /> <input type="reset" name="Submit2" value="Reset" /></td> </tr> </table> </td> </form> </tr> </table> <table width="400" border="0" align="center" cellpadding="3" cellspacing="0"> <tr> <td><strong><a href="viewguestbook.php">View Guestbook</a> </strong></td> </tr> </table> Code: [Select] <?php $mysql_host = "myhost"; $mysql_database = "guest"; $mysql_user = "myusername"; $mysql_password = "mypassword"; //$db_name="guest"; This is not needed, as db_name is $mysql_database above, so please delete this line. $tbl_name="guestbook"; // Table name // Connect to server and select database. mysql_connect("$mysql_host", "$mysql_user", "$mysql_password") or die("cannot connect server "); mysql_select_db("$mysql_database") or die("cannot select DB"); $name = $_POST['name']; $email = $_POST['email']; $comment = $_POST['comment']; $datetime=date("y-m-d h:i:s"); //date time $sql="INSERT INTO $tbl_name (name, email, comment, datetime) VALUES ('$name', '$email', '$comment', '$datetime')"; $result=mysql_query($sql); //check if query successful if($result){ echo "Successful"; echo "<BR>"; echo "<a href='viewguestbook.php'>View guestbook</a>"; // link to view guestbook page } else { echo "ERROR"; } mysql_close(); ?> Code: [Select] <table width="400" border="0" align="center" cellpadding="3" cellspacing="0"> <tr> <td><strong>View Guestbook | <a href="guestbook.php">Sign Guestbook</a> </strong></td> </tr> </table> <br> <?php $mysql_host = "myhost"; $mysql_database = "guest"; $mysql_user = "myusername"; $mysql_password = "mypassword"; $tbl_name="guestbook"; // Table name // Connect to server and select database. mysql_connect("$mysql_host", "$mysql_user", "$mysql_password") or die("cannot connect server "); mysql_select_db("$mysql_database") or die("cannot select DB"); $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); while($rows=mysql_fetch_array($result)){ ?> <table width="400" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td><table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF"> <tr> <td>ID</td> <td>:</td> <td><? echo $rows['id']; ?></td> </tr> <tr> <td width="117">Name</td> <td width="14">:</td> <td width="357"><? echo $rows['name']; ?></td> </tr> <tr> <td>Email</td> <td>:</td> <td><? echo $rows['email']; ?></td> </tr> <tr> <td valign="top">Comment</td> <td valign="top">:</td> <td><? echo nl2br($rows['comment']); ?></td> </tr> <tr> <td valign="top">Date/Time </td> <td valign="top">:</td> <td><? echo $rows['datetime']; ?></td> </tr> </table></td> </tr> </table> <BR> <? } mysql_close(); //close database ?> I have a simple guestbook set up. Even when I set the max post size to 6000000 (if you're wondering why Id allow that its cause I'm just using it as a private message board with one other person), after a certain amount of characters, it splits the post up into several messages and in place of the name of the poster, it's an IP. Any ideas why this is happening? Thanks. Hi, I've just installed a guestbook but when posting a message (signing in) it shows 'no entries yet'. On clicking the submit a very quick screen splashes up with a load of writing out of whoch I could just read ...line function open data file... You can check it out at www.qualitycarersdirect.com/careasp/portal.asp then click on 'post on the baord' it is a php file. Dear people here at phpfreaks
I am working on updating an old guestbook with outdated code (predecated). I will follow the suggestions I have received here on this forum already by using the new MySQL PDO technique. I am pretty rusty on PHP and MySQL, since I haven't been using it for years. So it took me a while to get Xampp running and installing Virtual hosts, so I can test my code locally. This is all working now. I have decided to start from scratch, building my guestbook up gradually in order to be able to understand each step better. I am inspired by the following tutorial:
http://wiki.hashphp....ySQL_Developers
So far I have created four files
1. contribution_to_guestbook.html
2. put_in_guestbook.php
3. show_content_of_guestbook.php
4. mysql_functions.php
The guestbook is implemented as a table with the name guestbook in the MySQL database with the name my_database. The database contains six fields, which a id, time, ip, name, email and contribution. The user can write a contribution by filling in his name, email address and contribution in the form placed in the first file. These data for the fields name, email and contribution respectively are being sent to the second file. At the same time the datetime is automatically registered along with the IP address of the users computer in the fields time and ip. When inserted in the table in the database via the second file, the primary field id is automatically added and incremented by 1. After the insertion in the database, the user is directed to file 3, where the content of the whole guestbook is being displayed for the user to see. The 4th file is containing the connection details for the database, including the password.
NB! The IP address of the users computer is not being displayed but only collected in the case one want to block spammers from specific computers with fixed IP addresses. In order to better block for spam from computer bots, I will later place a question in the first file to only admit humans ...
My questions
Is the structure of my guestbook convenient? Would it be appropriate to create functions to make the code more readable and if so, how can I do it? I wanted to make a prepared statement in the 3. file in which I select the content on the guestbook in order to display it. Can it be done, and if so how do the code look like? I know I need more error handling. Also I need to test user input. For example if no contribution is being written, an error message should be shown to the user, etc. Do you have some suggestions here and how to do it? What about security? I hope the password for my database will not be accessible in any way? I will appreciate any comments on the four questions above and eventual something else I have overlooked! I hope my thread is not too long. Hope for some replies ... Here is my code so far (still just a framework!): 1. contribution_to_guestbook.html <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Contribution to Guestbook</title> <style type="text/css"> body,td,th {font-family: Verdana, Geneva, sans-serif;} form1 table tr td {color: #06C;} h1 {color: #0000A0;} </style> </head> <body> <form method="POST" action="put_in_guestbook.php"> <h1>Contribution to Guestbook</h1> <table border="0" cellspacing="5" cellpadding="5"> <tr> <td>Name</td> <td> <INPUT type="text" name="name" size=40 maxlength=100> </td> </tr> <tr> <td>Email</td> <td> <INPUT type="text" name="email" size=40 maxlength=100> </td> </tr> <tr> <td valign="top">Contribution</td> <td> <TEXTAREA name="contribution" cols=60 rows=10></TEXTAREA> </td> </tr> <tr> <td></td> <td align="center"> <INPUT type="submit" value="Submit contribution"> </td> </tr> </table> </form> <p></p> </body> </html>2. put_in_guestbook.php <?php require("mysql_functions.php"); $ip = $_SERVER['REMOTE_ADDR']; //Clients IP address collected $name = $_POST['name']; //Data from input form etc. $email = $_POST['email']; $contribution = $_POST['contribution']; try { $db = new PDO('mysql:host='.$server.';dbname='.$database.';charset=utf8mb4', $username, $password); //Connecting to database $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $stmt = $db->prepare("INSERT INTO guestbook(`time`, `ip`, `name`, `email`, `contribution`) VALUES(NOW(), ?, ?, ?, ?)"); $stmt->execute(array($ip, $name, $email, $contribution)); //Placing the new contribution with details in Guestbook $db = NULL; //Closing database header("Location: show_content_of_guestbook.php"); //Redirecting to another page to show content of guestbook } catch(PDOException $ex) { echo "Could not insert into guestbook"; } ?>3. show_content_of_guestbook.php <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf8mb4" /> <title>Guestbook</title> </head> <body> <?php require("mysql_functions.php"); header('Content-Type: text/html; charset=utf-8'); try { $db = new PDO('mysql:host='.$server.';dbname='.$database.';charset=utf8mb4', $username, $password); //Connecting to database $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); foreach ($db->query('SELECT * FROM guestbook') as $row) { echo "Contribution number: ".$row['id']."<br/>"; echo "Time: ".$row['time']."<br/>"; echo "Name: ".$row['name']."<br/>"; echo "Email: ".$row['email']."<br/>"; echo "Contribution: ".$row['contribution']."<br/>"."<br/>"; $db=NULL; //Closing database } } catch(PDOException $ex) { echo "An error ocurred"; } ?> </body> </html>4. mysql_functions.php <?php $server = 'localhost'; $username = 'root'; $password = 'my_password'; $database = 'my_database'; ?>Regards, Erik Edited by erikla, 16 July 2014 - 07:52 AM. Hi I just implementet a PHP Guestbook in my Flash site, and it works almost perfectly. But i have one problem. Every time i try to write on the guestbook, and include a Colon : <---- , it wont work. How do i make it work? You can see the guestbook he http://www.meny-graphics.dk/blog by pressing "Mere" under the first entry, and scrolling down. The PHP file can be found he http://www.meny-graphics.dk/blog/GuestBook.php Thanks in advance! I have created a php guestbook for my site. The only problem I have with it is that when a user puts a carriage return in their entry, it is not replicated in the viewed post. I'm trying to figure out how I turn these returns into <br /> tags for display. Do I do something with the php that handles the input (i.e. somehow replace carriage returns with <br />'s) or is it to do with the output php code? Any pointers would be gratefully appreciated. This is the php for the guestbook entries output: Code: [Select] <?php include "connection.php"; $table = "guestbook"; $data = mysql_query("SELECT * FROM $table ORDER BY id DESC") or die(mysql_error()); echo "<div class='divide_message'>"; while($info = mysql_fetch_array( $data )) { $date = date("d/m/y",strtotime($info['date'])); echo "<div class='block message'>"; echo "<div class='message_name'>" . $info['name'] . ""; echo "<span class='date'>" . $date . "</span></div><br />"; echo "<div class='message_message'>" . $info['message'] . "</div>"; echo "</div>"; } echo "</div>"; ?> Hi everyone! I've been working on a php script to replace links that contain a query with direct links to the files they would redirect to. I'm having trouble echoing $year in my script. Listed below is the script, just below ,$result = mysql_query("SELECT * FROM $dbname WHERE class LIKE '%$search%'") or die(mysql_error());, in the script I try to echo $year. It doesn't show up in the table on the webpage. Everything else works fine. Any help wold be appreciated greatly. Thanks in advance. <?php include 'config2.php'; $search=$_GET["search"]; // Connect to server and select database. mysql_connect($dbhost, $dbuser, $dbpass)or die("cannot connect"); mysql_select_db("vetman")or die("cannot select DB"); $result = mysql_query("SELECT * FROM $dbname WHERE class LIKE '%$search%'") or die(mysql_error()); // store the record of the "" table into $row //$current = ''; echo "<table align=center border=1>"; echo "<br>"; echo "<tr>"; echo "<td align=center>"; ?> <div style="float: center;"><a><h1><?php echo $year; ?></h1></a></div> <?php echo "</td>"; echo "</tr>"; echo "</table>"; // keeps getting the next row until there are no more to get if($result && mysql_num_rows($result) > 0) { $i = 0; $max_columns = 2; echo "<table align=center>"; echo "<br>"; while($row = mysql_fetch_array($result)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; echo "<td align=center>"; ?> <div style="float: left;"> <div><img src="<?php echo $image1; ?>"></div> </div> <?php echo "</td>"; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while } // end if results // clean up table - makes your code valid! if($i > 0) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; echo '</tr>'; } mysql_close(); ?> </table> Hi i have this upload script which works fine it uploads image to a specified folder and sends the the details to the database. but now i am trying to instead make a modify script which is Update set so i tried to change insert to update but didnt work can someone help me out please this my insert image script which works fine but want to change to modify instead Code: [Select] <?php mysql_connect("localhost", "root", "") or die(mysql_error()) ; mysql_select_db("upload") or die(mysql_error()) ; // my file the name of the input area on the form type is the extension of the file //echo $_FILES["myfile"]["type"]; //myfile is the name of the input area on the form $name = $_FILES["image"] ["name"]; // name of the file $type = $_FILES["image"]["type"]; //type of the file $size = $_FILES["image"]["size"]; //the size of the file $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name $error =array(); // this an empty array where you can then call on all of the error messages $allowed_exts = array('jpg', 'jpeg', 'png', 'gif'); // array with the following extension name values $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif'); // array with the following image type values $location = 'images/'; //location of the file or directory where the file will be stored $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg //echo $extension = substr($name, 3); //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg // another way of doing is with explode // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode $myfile = $_POST["myfile"]; if (isset($image)) // if you choose a file name do the if bellow { // if extension is not equal to any of the variables in the array $allowed_exts error appears if(in_array($extension, $allowed_exts) === false ) { $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line } // if file type is not equal to any of the variables in array $image_type error appears if(in_array($type, $image_type) === false) { $error[] = 'Type of file not allowed! only images allowed<br />'; } // if file bigger than the number bellow error message if($size > 2097152) { $error[] = 'File size must be under 2MB!'; } // check if folder exist in the server if(!file_exists ($location)) { $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location; } } // if no error found do the move upload function if (empty($error)){ if (move_uploaded_file($temp, $location .$appendic_name)) { // insert data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image mysql_query("INSERT INTO image (myfile ,image) VALUES ('$myfile', '$appendic_name')") ; exit(); } } else { foreach ($error as $error) { echo $error; } } //echo $type; ?> I'm trying to use this script known as SimpleImage.php that can be found here <a href="http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php">link</a> I'm trying to include what is on the bottom of the page to my existing script can anyone help me I've tried several ways but its not working. Code: [Select] <?php session_start(); error_reporting(E_ALL); ini_set('display_errors','On'); //error_reporting(E_ALL); // image upload folder $image_folder = 'images/classified/'; // fieldnames in form $all_file_fields = array('image1', 'image2' ,'image3', 'image4'); // allowed filetypes $file_types = array('jpg','gif','png'); // max filesize 5mb $max_size = 5000000; //echo'<pre>';print_r($_FILES);exit; $time = time(); $count = 1; foreach($all_file_fields as $fieldname){ if($_FILES[$fieldname]['name'] != ''){ $type = substr($_FILES[$fieldname]['name'], -3, 3); // check filetype if(in_array(strtolower($type), $file_types)){ //check filesize if($_FILES[$fieldname]['size']>$max_size){ $error = "File too big. Max filesize is ".$max_size." MB"; }else{ // new filename $filename = str_replace(' ','',$myusername).'_'.$time.'_'.$count.'.'.$type; // move/upload file $target_path = $image_folder.basename($filename); move_uploaded_file($_FILES[$fieldname]['tmp_name'], $target_path); //save array with filenames $images[$count] = $image_folder.$filename; $count = $count+1; }//end if }else{ $error = "Please use jpg, gif, png files"; }//end if }//end if }//end foreach if($error != ''){ echo $error; }else{ /* -------------------------------------------------------------------------------------------------- SAVE TO DATABASE ------------------------------------------------------------------------------------ -------------------------------------------------------------------------------------------------- */ ?> hey guys im really just after a bit of help/information on 2 things (hope its in the right forum).
1. basically I'm wanting to make payments from one account to another online...like paypal does...im wondering what I would need to do to be able to do this if anyone can shine some light please?
2.as seen on google you type in a query in the search bar and it generates sentences/keywords from a database
example:
so if product "chair" was in the database
whilst typing "ch" it would show "chair" for a possible match
I know it would in tale sql & json but im after a good tutorial/script of some sort.
if anyone can help with some information/sites it would be much appreciated.
Thank you
Hello, I stored a fsockopen function in a separate "called.php" file, in order to run it as another thread when it needs. The called script should return results to the "master.php" script. I'm able to run the script to get the socket working, and I'm able to get results from the called script. I tried for hours but I can't do the twice both My master.php script (with socket working): Code: [Select] <?php $command = "(/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR] &) > /dev/null"; $result = exec($command); echo ("result = $result\r\n"); ?> and my called.php script Code: [Select] #!/mnt/opt/usr/bin/php-cli -q <?php $device = $_SERVER['argv'][1]; $port = "8080"; $fp = fsockopen($device, $port, $errno, $errstr, 5); fwrite($fp, "test"); fclose($fp); echo ("normal end of the called.php script"); ?> In the master script, if I use Code: [Select] $command = "(/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR] &) > /dev/null"; the socket works, but I have nothing in $result (note also that I don't anderstand why the ( ... &) are needed!?) and if I use Code: [Select] $command = "/mnt/opt/www/called.php $_SERVER[REMOTE_ADDR]"; I have the correct text "normal end of the called.php script" in $result but the socket connection is not performed (no errors in php logs) Could you help me to find a way to let's work the two features correctly together? Thank you. Well the subject line is pretty explicit. I found this script that uploads a picture onto a folder on the server called images, then inserts the the path of the image on the images folder onto a VACHAR field in a database table. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "images/"; // Get our POSTed variable $image = $_FILES['image']; // Sanitize our input $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved to // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: member.php"); exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: member.php"); exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { $_SESSION['error'] = "A file with that name already exists"; header("Location: member.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: images.php"); echo "File uploaded"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: member.php"); exit; } } //End of if session variable id is not present. ?> The script seems to work fine because I managed to upload a picture which was successfully inserted into my images folder and into the database. Now the problem is, I can't figure out exactly how to write the script that displays the image on an html page. I used the following script which didn't work. Code: [Select] //authenticate user //Start session session_start(); //Connect to database require ('config.php'); $sql = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($sql); $imagebytes = $row['image']; header("Content-type: image/jpeg"); print $imagebytes; Seems to me like I need to alter some variables to match the variables used in the insert script, just can't figure out which. Can anyone help?? |