PHP - Search Name And Pull Information - Mysql
I don't know that the subject describes exactly what I want to do so I will explain it as best as I can.
I have a form that uses a select box to pull all the names of our employees from the database. I then have a submit button that opens up a page. The code from my view.php is as follows: <form onsubmit="return validateForm()" name="frmRequest" action="attendance.php" method="post" encytype="multipart/form-data"> Which employee would you like? <select> <? @ $db = mysql_connect("localhost", "db_user", "db_pass"); mysql_select_db("EmployeeInfo"); $strSQL = "SELECT Name FROM EmployeeInfo ORDER BY Name"; $rs = mysql_query($strSQL); $nr = mysql_num_rows($rs); for ($i=0; $i<$nr; $i++) { $r = mysql_fetch_array($rs); echo "<OPTION VALUE=\"".$r["Name"]."\">".$r["Name"]."</OPTION>"; } ?> </select> <input type="submit" class="submit" value="Submit" /> </form> On the attendance.php form, I need it to display that user that was pulled from the form on the page before. What would be the best way to do this? I am fairly new to PHP and i'm at a loss right now. Thanks, dmcdaniel Similar TutorialsOn the home page I am having a problem pulling information from the MySql here is my code...and this is what I am trying to do... i am trying to pull 10 items from the database that have today's date...I am also trying to make the user name a link to a page called backpack.php where that page can use the user name that is clicked to retrieve more information. (the problem I am having is 10 results come up but it is a repeat of the same 10 results and when you click the link it doesn't show the user that is clicked info.) PLEASE someone help I have been trying to figure this out for the longest time. Code: [Select] <form action="backpack.php" method="post"> <?php // rows to return $limit=10; $idcount=10; $date = date('Y-m-d'); $count = 0; while ($limit>=$count) { //open database $connect = mysql_connect("hostname","uname","pass") or die("Not connected"); mysql_select_db("db_name") or die("could not log in"); $query = "SELECT *,COUNT(name) FROM boox WHERE date='$date' ORDER BY date"; $idcount = $row['COUNT(name)']; $result = mysql_query($query); while($row = mysql_fetch_array($result)) echo "</br><table width='297' height='200' border='1' align='center' style='overflow:scroll'> <tr> <td width='152'>Book Title:</td> <td width='129'>$row[name]</td> </tr> <tr> <td>Author:</td> <td>$row[author]</td> </tr> <tr> <td>ISBN#</td> <td>$row[isbn]</td> </tr> <tr> <td>Date Posted:</td> <td>$row[date]</td> </tr> <tr> <td>Posted By:</td> <td><a href='backpack.php' onclick='document['packback'].submit()'>$row[username]</a></td> </tr> <tr> <td>School:</td> <td>$row[school]</td> </tr> </table></br>"; $count = $count + 1; $idcount = idcount + 1; } ?> </form> MOD EDIT: DB credentials removed, [code] . . . [/code] tags added. Hello all, I have a membership website which is using sessions... and ive been asked to add some promotion points system. So that each user is able to see how many promotion points they have... Now, I'm a beginner in mysql and php, but feel I'm learning fairly quickly. What I need help with, is to be able to display the amount of promotion points for the logged in user. I created a new field in my "essenti1_Users" table for the promotion code. database is called "essenti1_membership" table is "essenti1_Users" feild is "promo" I think im going to have to manually add the points to each user manually through phpMyAdmin Navicat unfortunatly. Unless anyone has any other ideas just for adding the points to each user account? ziggynerja is online now Add to ziggynerja's Reputation Report Post Edit/Delete Message Hi all, I have a number of tables within a mysql database and I'm stuck on how to pull information from one based on the results being displayed by another. The site shows items for sale where by all the product information is held in tablea, when an individual item is being displayed I need to be able to pull a manufacturer profile from tableb based on the manufacturer name stored in tablea column profile. The manufacturer name is already being called into the page by existing code as the site has always shown the manufacturer name, I just can't work out out to pull the new profile information in as well from the new table. Any help appreciated Iain Hi, I have a 'pre-release' sign up form, where people put in their email address and name, and it transmits to a MYSQL database. That's working fine. What I want to do is to have a piece of text that reads: (insert pre release amount of signer upperers here) have signed up. Will you? I'm guessing that the amount of rows on the table, would end up being the number. How do I do this? Thanks, Jack Need some help I have 2 tables in a database and I need to search the first table and use the results from that search, to search another table, can this be done? and if it can how would you recommend that I go about it? Thanks For Your Help Guys! The result pages is supposed to have pagination like google help me please
Hi all How do I modify the below code to search multiple tables in mySQL database? $query = "select * from store_items where description like \"%$trimmed%\" or title like \"%$trimmed%\" or dimensions like \"%$trimmed%\" order by id ASC"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); It is for a search function and I need it to search another table called 'about_text' and 'faq_text' Thanks Pete hello i am trying to display account name in a persons profile, when i do it, it just displays Resource id #21 Resource id #22 Resource id #23 Resource id #24 Resource id #25 Resource id #26 instead of showing the admin, or user here is the code to display the account name Code: [Select] / Get all the data from the "myMembers" table $result = mysql_query("SELECT * FROM myMembers") or die(mysql_error()); echo "<table border='0'>"; echo "<tr> <th>Name</th></tr>"; // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into a table echo "<tr><td>"; echo mysql_query("SELECT account_name FROM myMembers WHERE id='{$_SESSION['id']}' LIMIT 1"); echo "</td><td>"; } echo "</table>"; ?> and here is the whole code for the page Code: [Select] <?php // Start_session, check if user is logged in or not, and connect to the database all in one included file include_once("scripts/checkuserlog.php"); // Include the class files for auto making links out of full URLs and for Time Ago date formatting include_once("wi_class_files/autoMakeLinks.php"); include_once ("wi_class_files/agoTimeFormat.php"); // Create the two new objects before we can use them below in this script $activeLinkObject = new autoActiveLink; $myObject = new convertToAgo; ?> <?php // ------- INITIALIZE SOME VARIABLES --------- // they must be initialized in some server environments or else errors will get thrown $id = ""; $username = ""; $firstname = ""; $lastname = ""; $mainNameLine = ""; $country = ""; $state = ""; $city = ""; $zip = ""; $bio_body = ""; $website = ""; $youtube = ""; $facebook = ""; $twitter = ""; $twitterWidget = ""; $accounttype = ""; $locationInfo = ""; $user_pic = ""; $blabberDisplayList = ""; $interactionBox = ""; $cacheBuster = rand(999999999,9999999999999); // Put on an image URL will help always show new when changed // ------- END INITIALIZE SOME VARIABLES --------- // ------- ESTABLISH THE PAGE ID ACCORDING TO CONDITIONS --------- if (isset($_GET['id'])) { $id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers } else if (isset($_SESSION['idx'])) { $id = $logOptions_id; } else { header("location: index.php"); exit(); } // ------- END ESTABLISH THE PAGE ID ACCORDING TO CONDITIONS --------- /*### New form stuff created by PaulRyan [paul_mc_2k6@hotmail.co.uk] ###*/ if(isSet($_POST['friendPost']) && strtolower($_POST['friendPost']) == 'blab' && $_POST['blab_field'] != "" && $_POST['blab_field'] != " ") { $blab = strip_tags(mysql_real_escape_string($_POST['blab_field'])); $addBlab = mysql_query("INSERT INTO blabbing (`mem_id`,`send_id`,`the_blab`,`blab_date`) VALUES ('$id','{$_SESSION['id']}','$blab',now())"); /*### [E-mail Notifications] - added by PaulRyan - [paul_mc_2k6@hotmail.co.uk] ###*/ /*################################################################################*/ if($id != $_SESSION['id'] && $addBlab) { $senderInfo = mysql_query("SELECT username FROM myMembers WHERE id='{$_SESSION['id']}' LIMIT 1"); $recieverInfo = mysql_query("SELECT username,email FROM myMembers WHERE id=$id LIMIT 1"); if(mysql_num_rows($senderInfo) && mysql_num_rows($recieverInfo)) { $senderInfo = mysql_fetch_assoc($senderInfo); $senderName = $senderInfo['username']; $recieverInfo = mysql_fetch_assoc($recieverInfo); $recieverName = $recieverInfo['username']; $sendTo = $recieverInfo['email']; $subject = 'You have a new wall post'; $headers = "From: Cookbookers [No-Reply] <notifications@cookbookers.com>m\r\n"; $headers .= "Reply-To: notifications@cookbookers.com\r\n"; $headers .= "Return-Path: notifications@cookbookers.com\r\n"; $headers .= "CC: notifications@cookbookers.com\r\n"; $headers .= "BCC: notifications@cookbookers.com\r\n"; $message = "Hello $recieverName. \n\n". "$senderName has posted the following message on your wall: \n". "-------------------- \n". "$blab \n". "-------------------- \n\n". "Please login to reply to this wall post. \n". "Login URL: http://cookbookers.com/login.php \n\n". "Thanks, CookBookers Team. \n\n". "If this message appears in your junk folder, please add notifications@cookbookers.com to your contact list."; $message = wordwrap($message, 70); mail($sendTo, $subject, $message, $headers); } } /*################################################################################*/ /*### [E-mail Notifications] - added by PaulRyan - [paul_mc_2k6@hotmail.co.uk] ###*/ header('Location: profile.php?id='.$id.''); exit; } /*### New form stuff created by PaulRyan [paul_mc_2k6@hotmail.co.uk] ###*/ // ------- FILTER THE ID AND QUERY THE DATABASE -------- $id = preg_replace('#[^0-9]#i', '', $id); // filter everything but numbers on the ID just in case $sql = mysql_query("SELECT * FROM myMembers WHERE id='$id' LIMIT 1"); // query the member // ------- FILTER THE ID AND QUERY THE DATABASE -------- // ------- MAKE SURE PERSON EXISTS IN DATABASE --------- $existCount = mysql_num_rows($sql); // count the row nums if ($existCount == 0) { // evaluate the count header("location: index.php?msg=user_does_not_exist"); exit(); } // ------- END MAKE SURE PERSON EXISTS IN DATABASE --------- // ------- WHILE LOOP FOR GETTING THE MEMBER DATA --------- while($row = mysql_fetch_array($sql)){ $username = $row["username"]; $firstname = $row["firstname"]; $lastname = $row["lastname"]; $country = $row["country"]; $state = $row["state"]; $city = $row["city"]; $sign_up_date = $row["sign_up_date"]; $sign_up_date = strftime("%b %d, %Y", strtotime($sign_up_date)); $last_log_date = $row["last_log_date"]; $last_log_date = strftime("%b %d, %Y", strtotime($last_log_date)); $bio_body = $row["bio_body"]; $bio_body = str_replace("&#39;", "'", $bio_body); $bio_body = stripslashes($bio_body); $website = $row["website"]; $youtube = $row["youtube"]; $facebook = $row["facebook"]; $twitter = $row["twitter"]; $friend_array = $row["friend_array"]; /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $check_pic = "members/$id/image01.jpg"; $default_pic = "members/0/image01.jpg"; if (file_exists($check_pic)) { $user_pic = "<img src=\"$check_pic?$cacheBuster\" width=\"218px\" />"; } else { $user_pic = "<img src=\"$default_pic\" width=\"218px\" />"; } /////// Mechanism to Display Real Name Next to Username - real name(username) ////////////////////////// if ($firstname != "") {; $mainNameLine = "$firstname $lastname ($username)"; $username = $firstname; } else { $mainNameLine = $username; } /////// Mechanism to Display Youtube channel link or not ////////////////////////// if ($youtube == "") { $youtube = ""; } else { $youtube = '<br /><br /><img src="images/youtubeIcon.jpg" width="18" height="12" alt="Youtube Channel for ' . $username . '" /> <strong>YouTube Channel:</strong><br /><a href="http://www.youtube.com/user/' . $youtube . '" target="_blank">youtube.com/' . $youtube . '</a>'; } /////// Mechanism to Display Facebook Profile link or not ////////////////////////// if ($facebook == "") { $facebook = ""; } else { $facebook = '<br /><br /><img src="images/facebookIcon.jpg" width="18" height="12" alt="Facebook Profile for ' . $username . '" /> <strong>Facebook Profile:</strong><br /><a href="http://www.facebook.com/profile.php?id=' . $facebook . '" target="_blank">profile.php?id=' . $facebook . '</a>'; } /////// Mechanism to Display Twitter Tweet Widget or not ////////////////////////// if ($twitter == "") { $twitterWidget = ""; } else { $twitterWidget = "<script src=\"http://widgets.twimg.com/j/2/widget.js\"></script> <script> new TWTR.Widget({ version: 2, type: 'profile', rpp: 5, interval: 6000, width: 218, height: 160, theme: { shell: { background: '#BDF', color: '#000000' }, tweets: { background: '#ffffff', color: '#000000', links: '#0066FF', } }, features: { scrollbar: true, loop: false, live: false, hashtags: true, timestamp: true, avatars: false, behavior: 'all' } }).render().setUser('$twitter').start(); </script>"; } /////// Mechanism to Display Website URL or not ////////////////////////// if ($website == "") { $website = ""; } else { $website = '<br /><br /><img src="images/websiteIcon.jpg" width="18" height="12" alt="Website URL for ' . $username . '" /> <strong>Website:</strong><br /><a href="http://' . $website . '" target="_blank">' . $website . '</a>'; } /////// Mechanism to Display About me text or not ////////////////////////// if ($bio_body == "") { $bio_body = ""; } else { $bio_body = '<div class="infoBody">' . $bio_body . '</div>'; } /////// Mechanism to Display Location Info or not ////////////////////////// if ($country == "" && $state == "" && $city == "") { $locationInfo = ""; } else { $locationInfo = "$city · $state<br />$country ".'<a href="#" onclick="return false" onmousedown="javascript:toggleViewMap(\'google_map\');">view map</a>'; } } // close while loop // ------- END WHILE LOOP FOR GETTING THE MEMBER DATA --------- // ------- POST NEW BLAB TO DATABASE --------- $blab_outout_msg = ""; if (isset($_POST['blab_field']) && isSet($_POST['submit']) && $_POST['submit'] == 'Blab' && $_POST['blab_field'] != "" && $_POST['blab_field'] != " "){ $blabWipit = $_POST['blabWipit']; $sessWipit = base64_decode($_SESSION['wipit']); if (!isset($_SESSION['wipit'])) { } else if ($blabWipit == $sessWipit) { // Delete any blabs over 50 for this member $sqlDeleteBlabs = mysql_query("SELECT * FROM blabbing WHERE mem_id='$id' ORDER BY blab_date DESC LIMIT 50"); $bi = 1; while ($row = mysql_fetch_array($sqlDeleteBlabs)) { $blad_id = $row["id"]; if ($bi > 20) { $deleteBlabs = mysql_query("DELETE FROM blabbing WHERE id='$blad_id'"); } $bi++; } // End Delete any blabs over 20 for this member $blab_field = $_POST['blab_field']; $blab_field = stripslashes($blab_field); $blab_field = strip_tags($blab_field); $blab_field = mysql_real_escape_string($blab_field); $blab_field = str_replace("'", "&#39;", $blab_field); $sql = mysql_query("INSERT INTO blabbing (mem_id, the_blab, blab_date) VALUES('$id','$blab_field', now())") or die (mysql_error()); $blab_outout_msg = ""; } header('Location: profile.php?id='.$id.''); exit; } // ------- END POST NEW BLAB TO DATABASE --------- // ------- MEMBER BLABS OUTPUT CONSTRUCTION --------- /////// Mechanism to Display Pic if (file_exists($check_pic)) { $blab_pic = '<div style="overflow:hidden; height:40px;"><a href="profile.php?id=' . $id . '"><img src="' . $check_pic . '" width="40px" border="0" /></a></div>'; } else { $blab_pic = '<div style="overflow:hidden; height:40px;"><a href="profile.php?id=' . $id . '"><img src="' . $default_pic . '" width="40px" border="0" /></a></div>'; } /////// END Mechanism to Display Pic $sql_blabs = mysql_query("SELECT id, send_id, mem_id, the_blab, blab_date FROM blabbing WHERE mem_id='$id' ORDER BY blab_date DESC LIMIT 20"); while($row = mysql_fetch_array($sql_blabs)){ $blabid = $row["id"]; $uid = $row['send_id'] != 0 ? $row['send_id'] : $row['mem_id'] ; $the_blab = $row["the_blab"]; $the_blab = ($activeLinkObject -> makeActiveLink($the_blab)); $blab_date = $row["blab_date"]; $convertedTime = ($myObject -> convert_datetime($blab_date)); $whenBlab = ($myObject -> makeAgo($convertedTime)); if($row['send_id'] != $row['mem_id'] && $row['send_id'] != 0) { $tUsername = mysql_fetch_assoc(mysql_query("SELECT username FROM myMembers WHERE id=$uid LIMIT 1")); $tUsername = $tUsername['username']; } else { $tUsername = $username; } $blabberDisplayList .= '<table style="background-color:#FFF; border:#999 1px solid; border-top:none;" cellpadding="5" width="100%"> <tr> <td width="10%" valign="top">' . $blab_pic . '</td> <td width="90%" valign="top" style="line-height:1.5em;"> <span class="greenColor textsize10">' . $whenBlab . ' <a href="profile.php?id=' . $uid . '">' . $tUsername . '</a> said:</span> <br />' . $the_blab . '</td></tr></table>'; } // ------- END MEMBER BLABS OUTPUT CONSTRUCTION --------- // ------- ESTABLISH THE PROFILE INTERACTION TOKEN --------- $thisRandNum = rand(9999999999999,999999999999999999); $_SESSION['wipit'] = base64_encode($thisRandNum); // Will always overwrite itself each time this script runs // ------- END ESTABLISH THE PROFILE INTERACTION TOKEN --------- // ------- EVALUATE WHAT CONTENT TO PLACE IN THE MEMBER INTERACTION BOX ------------------- // initialize some output variables $friendLink = ""; $the_blab_form = ""; if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION idx is set, AND it does not equal the profile owner's ID // SQL Query the friend array for the logged in viewer of this profile if not the owner $sqlArray = mysql_query("SELECT friend_array FROM myMembers WHERE id='" . $logOptions_id ."' LIMIT 1"); while($row=mysql_fetch_array($sqlArray)) { $iFriend_array = $row["friend_array"]; } $iFriend_array = explode(",", $iFriend_array); if (in_array($id, $iFriend_array)) { $friendLink = '<a href="#" onclick="return false" onmousedown="javascript:toggleInteractContainers(\'remove_friend\');">Remove Friend</a>'; } else { $friendLink = '<a href="#" onclick="return false" onmousedown="javascript:toggleInteractContainers(\'add_friend\');">Add as Friend</a>'; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $interactionBox = '<br /><br /><div class="interactionLinksDiv"> ' . $friendLink . ' <a href="#" onclick="return false" onmousedown="javascript:toggleInteractContainers(\'private_message\');">Private Message</a> </div><br />'; /*### Friend Wall Blabbing added by PaulRyan [paul_mc_2k6@hotmail.co.uk] ###*/ $friendArray = explode(',',$friend_array); if(in_array($_SESSION['id'],$friendArray)) { $the_blab_form = '<div style="background-color:#BDF; border:#999 1px solid; padding:8px;"> <form action="profile.php?id='.(int)$_GET['id'].'" method="post" enctype="multipart/form-data" name="blab_from"> <textarea name="blab_field" rows="3" style="width:99%;"></textarea> <strong>Blab away ' . $_SESSION['username'] . '</strong> (220 char max) <input name="friendPost" type="submit" value="Blab" /> </form></div>'; } else { $the_blab_form = '<div style="background-color:#BDF; border:#999 1px solid; padding:8px;"> Only '.$username.'\'s friends can post here. </div>'; } /*### Friend Wall Blabbing added by PaulRyan [paul_mc_2k6@hotmail.co.uk] ###*/ } else if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If SESSION idx is set, AND it does equal the profile owner's ID $interactionBox = '<br /><br /><div class="interactionLinksDiv"> <a href="#" onclick="return false" onmousedown="javascript:toggleInteractContainers(\'friend_requests\');">Friend Requests</a> </div><br />'; $the_blab_form = ' ' . $blab_outout_msg . ' <div style="background-color:#BDF; border:#999 1px solid; padding:8px;"> <form action="profile.php" method="post" enctype="multipart/form-data" name="blab_from"> <textarea name="blab_field" rows="3" style="width:99%;"></textarea> <input name="blabWipit" type="hidden" value="' . $thisRandNum . '" /> <strong>Blab away ' . $username . '</strong> (220 char max) <input name="submit" type="submit" value="Blab" /> </form></div>'; } else { // If no SESSION id is set, which means we have a person who is not logged in $interactionBox = '<div style="border:#CCC 1px solid; padding:5px; background-color:#E4E4E4; color:#999; font-size:11px;"> <a href="register.php">Sign Up</a> or <a href="login.php">Log In</a> to interact with ' . $username . ' </div>'; $the_blab_form = '<div style="background-color:#BDF; border:#999 1px solid; padding:8px;"> <textarea name="blab_field" rows="3" style="width:99%;"></textarea> <a href="register.php">Sign Up</a> or <a href="login.php">Log In</a> to write on ' . $username . '\'s Board </div>'; } // ------- END EVALUATE WHAT CONTENT TO PLACE IN THE MEMBER INTERACTION BOX ------------------- // ------- POPULATE FRIEND DISPLAY LISTS IF THEY HAVE AT LEAST ONE FRIEND ------------------- $friendList = ""; $friendPopBoxList = ""; if ($friend_array != "") { // ASSEMBLE FRIEND LIST AND LINKS TO VIEW UP TO 6 ON PROFILE $friendArray = explode(",", $friend_array); $friendCount = count($friendArray); $friendArray6 = array_slice($friendArray, 0, 6); $friendList .= '<div class="infoHeader">' . $username . '\'s Friends (<a href="#" onclick="return false" onmousedown="javascript:toggleViewAllFriends(\'view_all_friends\');">' . $friendCount . '</a>)</div>'; $i = 0; // create a varible that will tell us how many items we looped over $friendList .= '<div class="infoBody" style="border-bottom:#666 1px solid;"><table id="friendTable" align="center" cellspacing="4"></tr>'; foreach ($friendArray6 as $key => $value) { $i++; // increment $i by one each loop pass $check_pic = 'members/' . $value . '/image01.jpg'; if (file_exists($check_pic)) { $frnd_pic = '<a href="profile.php?id=' . $value . '"><img src="' . $check_pic . '" width="54px" border="1"/></a>'; } else { $frnd_pic = '<a href="profile.php?id=' . $value . '"><img src="members/0/image01.jpg" width="54px" border="1"/></a> '; } $sqlName = mysql_query("SELECT username, firstname FROM myMembers WHERE id='$value' LIMIT 1") or die ("Sorry we had a mysql error!"); while ($row = mysql_fetch_array($sqlName)) { $friendUserName = substr($row["username"],0,12); $friendFirstName = substr($row["firstname"],0,12);} if (!$friendUserName) {$friendUserName = $friendFirstName;} // If username is blank use the firstname... programming changes in v1.32 call for this if ($i % 6 == 4){ $friendList .= '<tr><td><div style="width:56px; height:68px; overflow:hidden;" title="' . $friendUserName . '"> <a href="profile.php?id=' . $value . '">' . $friendUserName . '</a><br />' . $frnd_pic . ' </div></td>'; } else { $friendList .= '<td><div style="width:56px; height:68px; overflow:hidden;" title="' . $friendUserName . '"> <a href="profile.php?id=' . $value . '">' . $friendUserName . '</a><br />' . $frnd_pic . ' </div></td>'; } } $friendList .= '</tr></table> <div align="right"><a href="#" onclick="return false" onmousedown="javascript:toggleViewAllFriends(\'view_all_friends\');">view all</a></div> </div>'; // END ASSEMBLE FRIEND LIST... TO VIEW UP TO 6 ON PROFILE // ASSEMBLE FRIEND LIST AND LINKS TO VIEW ALL(50 for now until we paginate the array) $i = 0; $friendArray50 = array_slice($friendArray, 0, 50); $friendPopBoxList = '<table id="friendPopBoxTable" width="100%" align="center" cellpadding="6" cellspacing="0">'; foreach ($friendArray50 as $key => $value) { $i++; // increment $i by one each loop pass $check_pic = 'members/' . $value . '/image01.jpg'; if (file_exists($check_pic)) { $frnd_pic = '<a href="profile.php?id=' . $value . '"><img src="' . $check_pic . '" width="54px" border="1"/></a>'; } else { $frnd_pic = '<a href="profile.php?id=' . $value . '"><img src="members/0/image01.jpg" width="54px" border="1"/></a> '; } $sqlName = mysql_query("SELECT username, firstname, country, state, city FROM myMembers WHERE id='$value' LIMIT 1") or die ("Sorry we had a mysql error!"); while ($row = mysql_fetch_array($sqlName)) { $funame = $row["username"]; $ffname = $row["firstname"]; $fcountry = $row["country"]; $fstate = $row["state"]; $fcity = $row["city"]; } if (!$funame) {$funame = $ffname;} // If username is blank use the firstname... programming changes in v1.32 call for this if ($i % 2) { $friendPopBoxList .= '<tr bgcolor="#F4F4F4"><td width="14%" valign="top"> <div style="width:56px; height:56px; overflow:hidden;" title="' . $funame . '">' . $frnd_pic . '</div></td> <td width="86%" valign="top"><a href="profile.php?id=' . $value . '">' . $funame . '</a><br /><font size="-2"><em>' . $fcity . '<br />' . $fstate . '<br />' . $fcountry . '</em></font></td> </tr>'; } else { $friendPopBoxList .= '<tr bgcolor="#E0E0E0"><td width="14%" valign="top"> <div style="width:56px; height:56px; overflow:hidden;" title="' . $funame . '">' . $frnd_pic . '</div></td> <td width="86%" valign="top"><a href="profile.php?id=' . $value . '">' . $funame . '</a><br /><font size="-2"><em>' . $fcity . '<br />' . $fstate . '<br />' . $fcountry . '</em></font></td> </tr>'; } } $friendPopBoxList .= '</table>'; // END ASSEMBLE FRIEND LIST AND LINKS TO VIEW ALL(50 for now until we paginate the array) } // ------- END POPULATE FRIEND DISPLAY LISTS IF THEY HAVE AT LEAST ONE FRIEND ------------------- ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta name="Description" content="Profile for <?php echo "$username"; ?>" /> <meta name="Keywords" content="<?php echo "$username, $city, $state, $country"; ?>" /> <meta name="rating" content="General" /> <meta name="ROBOTS" content="All" /> <title>Site Profile for <?php echo "$username"; ?></title> <link href="style/main.css" rel="stylesheet" type="text/css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <style type="text/css"> <!-- .infoHeader { background-color: #BDF; font-size:11px; font-weight:bold; padding:8px; border: #999 1px solid; border-bottom:none; width:200px; } .infoBody{ background-color: #FFF; font-size:11px; padding:8px; border: #999 1px solid; border-bottom:none; width:200px; } /* ------- Interaction Links Class -------- */ .interactionLinksDiv a { border:#B9B9B9 1px solid; padding:5px; color:#060; font-size:11px; background-image:url(style/headerBtnsBG.jpg); text-decoration:none; } .interactionLinksDiv a:hover { border:#090 1px solid; padding:5px; color:#060; font-size:11px; background-image:url(style/headerBtnsBGover.jpg); } /* ------- Interaction Containers Class -------- */ .interactContainers { padding:8px; background-color:#BDF; border:#999 1px solid; display:none; } #add_friend_loader { display:none; } #remove_friend_loader { display:none; } #interactionResults { display:none; font-size:16px; padding:8px; } #friendTable td{ font-size:9px; } #friendTable td a{ color:#03C; text-decoration:none; } #view_all_friends { background-image:url(style/opaqueDark.png); width:270px; padding:20px; position:fixed; top:150px; display:none; z-index:100; margin-left:50px; } #google_map { background-image:url(style/opaqueDark.png); padding:20px; position:fixed; top:150px; display:none; z-index:100; margin-left:50px; } #Layer1 { position:absolute; left:292px; top:170px; width:399px; height:230px; z-index:1; } #Layer2 { position:absolute; left:0px; top:532px; width:1103px; height:386px; z-index:2; } #Layer3 { position:absolute; left:255px; top:517px; width:111px; height:102px; z-index:3; } #Layer4 { position:absolute; left:304px; top:266px; width:637px; height:209px; z-index:4; } body { background-color: #3c60a4; background-image: url(images/bg.jpg); background-repeat: repeat-x; } --> </style> <script language="javascript" type="text/javascript"> // jQuery functionality for toggling member interaction containers function toggleInteractContainers(x) { if ($('#'+x).is(":hidden")) { $('#'+x).slideDown(200); } else { $('#'+x).hide(); } $('.interactContainers').hide(); } function toggleViewAllFriends(x) { if ($('#'+x).is(":hidden")) { $('#'+x).fadeIn(200); } else { $('#'+x).fadeOut(200); } } function toggleViewMap(x) { if ($('#'+x).is(":hidden")) { $('#'+x).fadeIn(200); } else { $('#'+x).fadeOut(200); } } // Friend adding and accepting stuff var thisRandNum = "<?php echo $thisRandNum; ?>"; var friendRequestURL = "scripts_for_profile/request_as_friend.php"; function addAsFriend(a,b) { $("#add_friend_loader").show(); $.post(friendRequestURL,{ request: "requestFriendship", mem1: a, mem2: b, thisWipit: thisRandNum } ,function(data) { $("#add_friend").html(data).show().fadeOut(12000); }); } function acceptFriendRequest (x) { $.post(friendRequestURL,{ request: "acceptFriend", reqID: x, thisWipit: thisRandNum } ,function(data) { $("#req"+x).html(data).show(); }); } function denyFriendRequest (x) { $.post(friendRequestURL,{ request: "denyFriend", reqID: x, thisWipit: thisRandNum } ,function(data) { $("#req"+x).html(data).show(); }); } // End Friend adding and accepting stuff // Friend removal stuff function removeAsFriend(a,b) { $("#remove_friend_loader").show(); $.post(friendRequestURL,{ request: "removeFriendship", mem1: a, mem2: b, thisWipit: thisRandNum } ,function(data) { $("#remove_friend").html(data).show().fadeOut(12000); }); } // End Friend removal stuff // Start Private Messaging stuff $('#pmForm').submit(function(){$('input[type=submit]', this).attr('disabled', 'disabled');}); function sendPM ( ) { var pmSubject = $("#pmSubject"); var pmTextArea = $("#pmTextArea"); var sendername = $("#pm_sender_name"); var senderid = $("#pm_sender_id"); var recName = $("#pm_rec_name"); var recID = $("#pm_rec_id"); var pm_wipit = $("#pmWipit"); var url = "scripts_for_profile/private_msg_parse.php"; if (pmSubject.val() == "") { $("#interactionResults").html('<img src="images/round_error.png" alt="Error" width="31" height="30" /> Please type a subject.').show().fadeOut(6000); } else if (pmTextArea.val() == "") { $("#interactionResults").html('<img src="images/round_error.png" alt="Error" width="31" height="30" /> Please type in your message.').show().fadeOut(6000); } else { $("#pmFormProcessGif").show(); $.post(url,{ subject: pmSubject.val(), message: pmTextArea.val(), senderName: sendername.val(), senderID: senderid.val(), rcpntName: recName.val(), rcpntID: recID.val(), thisWipit: pm_wipit.val() } , function(data) { $('#private_message').slideUp("fast"); $("#interactionResults").html(data).show().fadeOut(10000); document.pmForm.pmTextArea.value=''; document.pmForm.pmSubject.value=''; $("#pmFormProcessGif").hide(); }); } } // End Private Messaging stuff </script> </head> <body> <p> <?php include_once "header_template.php"; ?> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td style="border-top:0px" width="60%" valign="top"><br /> <table width="95%" border="0" align="center" cellpadding="6"> <tr> <td width="33%" valign="top"><?php echo $user_pic; ?> <?php echo $bio_body; ?> <div class="infoHeader"><?php echo $username; ?>'s Information</div> <div class="infoBody"> <?php echo $locationInfo; ?> <?php echo $website; ?> <?php echo $youtube; ?> <?php echo $facebook; ?> </div> <?php echo $friendList; ?> <div id="view_all_friends"> <div align="right" style="padding:6px; background-color:#FFF; border-bottom:#666 1px solid;"> <div style="display:inline; font-size:14px; font-weight:bold; margin-right:150px;">All Friends</div> <a href="#" onclick="return false" onmousedown="javascript:toggleViewAllFriends('view_all_friends');">close </a> </div> <div style="background-color:#FFF; height:240px; overflow:auto;"> <?php echo $friendPopBoxList; ?> </div> <div style="padding:6px; background-color:#000; border-top:#666 1px solid; font-size:10px; color: #0F0;"> Temporary programming shows 50 maximum. Navigating through the full list is coming soon. </div> </div> <?php echo $twitterWidget; ?> <div class="infoBody" style="border-bottom:#999 1px solid;"></div></td> <td width="67%" valign="top"><span style="font-size:16px; font-weight:800;"><?php echo $mainNameLine; ?></span> <?php echo $interactionBox; ?> <?php ////// admin thing// // Make a MySQL Connection mysql_connect("localhost", "cookbook_lmcgr44", "simon123") or die(mysql_error()); mysql_select_db("cookbook_cookbook") or die(mysql_error()); // Get all the data from the "example" table $result = mysql_query("SELECT * FROM myMembers") or die(mysql_error()); echo "<table border='0'>"; echo "<tr> <th>Name</th></tr>"; // keeps getting the next row until there are no more to get while($row = mysql_fetch_array( $result )) { // Print out the contents of each row into a table echo "<tr><td>"; echo mysql_query("SELECT account_name FROM myMembers WHERE id='{$_SESSION['id']}' LIMIT 1"); echo "</td><td>"; } echo "</table>"; ?> <? if (isset($_SESSION['idx']) && $logOptions_id == $id) { $sql_pm_check = mysql_query("SELECT id FROM private_messages WHERE to_id='$logOptions_id' AND opened='0'"); $num_new_pm = mysql_num_rows($sql_pm_check); if ($num_new_pm == 0) { echo "<div style='padding-left: 10px;'><a href=\"pm_inbox.php\"><font color='green' face='Arial'>".$num_new_pm." New Message</font></a></div>"; } if ($num_new_pm > 0) { echo "<div style='padding-left: 10px;'><a href=\"pm_inbox.php\"><font color='red' face='Arial'>".$num_new_pm." New Message</font></a></div>"; } } ?> <div class="interactContainers" id="add_friend"> <div align="right"><a href="#" onclick="return false" onmousedown="javascript:toggleInteractContainers('add_friend');">cancel</a> </div> Add <?php echo "$username"; ?> as a friend? <a href="#" onclick="return false" onmousedown="javascript:addAsFriend(<?php echo $logOptions_id; ?>, <?php echo $id; ?>);">Yes</a> <span id="add_friend_loader"><img src="images/loading.gif" width="28" height="10" alt="Loading" /></span> </div> <div class="interactContainers" id="remove_friend"> <div align="right"><a href="#" onclick="return false" onmousedown="javascript:toggleInteractContainers('remove_friend');">cancel</a> </div> Remove <?php echo "$username"; ?> from your friend list? <a href="#" onclick="return false" onmousedown="javascript:removeAsFriend(<?php echo $logOptions_id; ?>, <?php echo $id; ?>);">Yes</a> <span id="remove_friend_loader"><img src="images/loading.gif" width="28" height="10" alt="Loading" /></span> </div> <!-- START DIV that serves as an interaction status and results container that only appears when we instruct it to --> <div id="interactionResults" style="font-size:15px; padding:10px;"></div> <!-- END DIV that serves as an interaction status and results container that only appears when we instruct it to --> <!-- START DIV that contains the Private Message form --> <div class="interactContainers" id="private_message"> <form action="javascript:sendPM();" name="pmForm" id="pmForm" method="post"> <font size="+1">Sending Private Message to <strong><em><?php echo "$username"; ?></em></strong></font><br /> <br /> Subject: <input name="pmSubject" id="pmSubject" type="text" maxlength="64" style="width:98%;" /> Message: <textarea name="pmTextArea" id="pmTextArea" rows="8" style="width:98%;"></textarea> <input name="pm_sender_id" id="pm_sender_id" type="hidden" value="<?php echo $_SESSION['id']; ?>" /> <input name="pm_sender_name" id="pm_sender_name" type="hidden" value="<?php echo $_SESSION['username']; ?>" /> <input name="pm_rec_id" id="pm_rec_id" type="hidden" value="<?php echo $id; ?>" /> <input name="pm_rec_name" id="pm_rec_name" type="hidden" value="<?php echo $username; ?>" /> <input name="pmWipit" id="pmWipit" type="hidden" value="<?php echo $thisRandNum; ?>" /> <span id="PMStatus" style="color:#F00;"></span> <br /> <input name="pmSubmit" type="submit" value="Submit" /> or <a href="#" onclick="return false" onmousedown="javascript:toggleInteractContainers('private_message');">Close</a> <span id="pmFormProcessGif" style="display:none;"><img src="images/loading.gif" width="28" height="10" alt="Loading" /></span> </form> </div> <!-- END DIV that contains the Private Message form --> <div class="interactContainers" id="friend_requests" style="background-color:#FFF; height:240px; overflow:auto;"> <div align="right"><a href="#" onclick="return false" onmousedown="javascript:toggleInteractContainers('friend_requests');">close window</a> </div> <h3>The following people are requesting you as a friend</h3> <?php $sql = "SELECT * FROM friends_requests WHERE mem2='$id' ORDER BY id ASC LIMIT 50"; $query = mysql_query($sql) or die ("Sorry we had a mysql error!"); $num_rows = mysql_num_rows($query); if ($num_rows < 1) { echo 'You have no Friend Requests at this time.'; } else { while ($row = mysql_fetch_array($query)) { $requestID = $row["id"]; $mem1 = $row["mem1"]; $sqlName = mysql_query("SELECT username FROM myMembers WHERE id='$mem1' LIMIT 1") or die ("Sorry we had a mysql error!"); while ($row = mysql_fetch_array($sqlName)) { $requesterUserName = $row["username"]; } /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $check_pic = 'members/' . $mem1 . '/image01.jpg'; if (file_exists($check_pic)) { $lil_pic = '<a href="profile.php?id=' . $mem1 . '"><img src="' . $check_pic . '" width="50px" border="0"/></a>'; } else { $lil_pic = '<a href="profile.php?id=' . $mem1 . '"><img src="members/0/image01.jpg" width="50px" border="0"/></a>'; &nbs I have created a drop down list and it does retrieve information from mysql but now I want to use what is been selected to retrieve information. How Do I do this? <?php MYSQL_CONNECT(localhost,'root','') OR DIE("Unable to connect to database"); @mysql_select_db(Examination) or die( "Unable to select database"); $query=("SELECT * FROM subject"); $result=mysql_query($query) or die ("Unable to Make the Query:" . mysql_error() ); echo "<select name=myselect>"; while($row=mysql_fetch_array($result)){ echo "<OPTION VALUE=".$row['Sub_ID'].">".$row['Sub_Name']."</OPTION>"; } echo "</select>"; ?> Hi, I have a script that dumps the information from one of my MySQL tables into a CSV. The script works great, but in the result, the names of the MySQL columns are shown as-is. In other words, I have a column named "field4" that shows up as "field4" in the CSV. How can I modify the columns to more descriptive names without modifying the database itself? Here's my code: Code: [Select] <?php $host = "*********"; $user = "*********"; $pass = "*********"; $db = "database_name"; $table = "table"; $file = "member_information"; $link = mysql_connect($host, $user, $pass) or die("Cannot connect." . mysql_error()); mysql_select_db($db) or die("Cannot connect."); $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field'].","; $i++;} } $csv_output .= "\n"; $values = mysql_query("SELECT * FROM ".$table.""); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].", "; } $csv_output .= "\n"; } $filename = $file."_".date("m.d.y"); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("m.d.y") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; ?> The CSV it spits out looks like this: Code: [Select] field1 field2 field3 field 4 info info info info I want it to look like this: Code: [Select] Name Email Location Age info info info info Thanks in advance! Hi, I have created a session based logon system using php and MYSQL from some tutorials I found online which is working very successfully. I can log on and of and move through different pages with no problems. My query is how do I output or display the information that is specific to the user which is currently logged on and block access to any other users information. I am quite sure there is a simple solution that is escaping me. If you could point me in the right direction it would be greatly appreciated. Thanks in advance I Have a protected members section on my site for staff. I would like it so that information specific to that member of staff would appear on their homepage straight after login. Just basic information that is stored on a MySQL database so they can login and check appointments and clients etc for the week etc. is this something that is possible to do in PHP and MySQL? or am I going mad? At the moment I have the entire table on the members homepage and the only way I've figured out to specify a member to only show one users information is to use - (SELECT * FROM Tutors WHERE name = 'XXX'. I don't like this method as it would mean i would have to have a separate files for each member. I was hoping I could do something along the lines of - WHERE name = ' relative to the login name used'. but I am sure I am flogging a dead horse here. So many websites do this kind of thing and I'm surprised after scouring the net for hours and hours that I haven't found any useful information or tutorials on the subject. I am fairly new to programming in PHP and MySQL and am only just getting to grips with the lingo. Maybe I've just been seacrhing the wrong thing, I don't Know. Any help at all would be amazing and much appreciated, a nudge in the right direction would be a start as I'm getting nowhere on my own THANKS I am trying to make a filter to show posts from mutual friends between you and the persons profile you're on, I have somewhat of an idea on how to write the mysql query (it needs to be just one query, not two(which would be the easy way of doing it)). the "friends" table has: "friend_1" and "friend_2" and the "posts" table: "to_id" and "from_id" The PHP variables would be: "$session" and "$id" id would be the users Id of the profile you're on. Thanks, any help would be appreciated. My Php Buddies, I have mysql tbl columns these:
id: Now, I want to display their row data by excluded a few columns. Want to exclude these columns: date_&_time account_activation_code account_activation_status id_verification_video_file_url password
So, the User's (eg. your's) homepage inside his account should display labels like these where labels match the column names but the underscores are removed and each words' first chars CAPITALISED:
Id: 1
For your convenience only PART 1 works. Need help on Part 2 My attempted code:
PART 1 <?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to get columns from table $query = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'members' AND TABLE_NAME = 'users'"); while($row = $query->fetch_assoc()){ $result[] = $row; } // Array of all column names $columnArr = array_column($result, 'COLUMN_NAME'); foreach ($columnArr as $value) { echo "<b>$value</b>: ";?><br><?php } ?> PART 2 <?php //Display User Account Details echo "<h3>User: <a href=\"user.php?user=$user\">$user</a> Details</h3>";?><br> <?php $excluded_columns = array("date_&_time","account_activation_code","account_activation_status","id_verification_video_file_url","password"); foreach ($excluded_columns as $value2) { echo "Excluded Column: <b>$value2</b><br>"; } foreach ($columnArr as $value) { if($value != "$value2") { $label = str_replace("_"," ","$value"); $label = ucwords("$label"); //echo "<b>$label</b>: "; echo "$_SESSION[$value]";?><br><?php echo "<b>$label</b>: "; echo "${$value}";?><br><?php } } ?> PROBLEM: Columns from the excluded list still get displayed. Edited November 19, 2018 by phpsaneHey guys, I'm a newbie to PHP and MySql, and I need some help! For the record, I am a web developer and designer, who always put off learning , due to fear, but realized I had to do it. Anyways, my problem is this. I am creating a website, where there has to be a seach box where people can lookup names, and or keywords, that are stored into my db. I've googled it a billion times, and got everything to almost work. I know how to set-up a database, tables, insert info, and all the real basics of mysql. I am running my site on MAMP right now, and here is the code that I am trying to use. <?php /* DON'T DISPLAY ANY PHP ERRORS OR WARNINGS (optional) comment out in development -----------------------------------------------*/ error_reporting(0); /*DATABASE INFO --------------------------*/ $hostname_logon = 'localhost'; //Database server LOCATION $database_logon = ''; //Database NAME $username_logon = ''; //Database USERNAME $password_logon = ''; //Database PASSWORD /*MYSQL TABLE TO SEARCH --------------------------*/ //update these values to table you want to search $db_table = ''; //TABLE NAME $row_id = ''; //TABLE ROW ID $title_field = ''; //FIELD CONTAINING ITEM TITLE $content_field = ''; //FIELD CONTAINING ITEM CONTENT $link_field = ''; //FIELD CONTAINING ITEM URL $limit = 10; //NUMBER OF RESULTS PER PAGE /*SEARCH SCRIPT FILENAME --------------------------*/ //get the name of this file,so you can name this file whatever you want. This is used in the action parameter of the search form $currentFile = $_SERVER["SCRIPT_NAME"]; $parts = explode('/', $currentFile); $currentFile = $parts[count($parts) - 1]; /*CONNECT TO THE DATABASE --------------------------*/ //open database connection $connections = mysql_connect($hostname_logon, $username_logon, $password_logon) or die ( "Unabale to connect to the database" ); //select database mysql_select_db($database_logon) or die ( "Unable to select database!" ); /*GET SEARCH PARAMETERS --------------------------*/ //get the search parameter from URL $var = mysql_real_escape_string(@$_REQUEST['q']); //get pagination $s = mysql_real_escape_string(@$_REQUEST['s']); //set keyword character limit if(strlen($var) < 3){ $resultmsg = "<p>Search Error</p><p>Keywords with less then three characters are omitted...</p>" ; } //trim whitespace from the stored variable $trimmed = trim($var); $trimmed1 = trim($var); //separate key-phrases into keywords $trimmed_array = explode(" ",$trimmed); $trimmed_array1 = explode(" ",$trimmed1); // check for an empty string and display a message. if ($trimmed == "") { $resulterror = "<p>Search Error</p><p>Please enter a search...</p>" ; } // check for a search parameter if (!isset($var)){ $resulterror = "<p>Search Error</p><p>We don't seem to have a search parameter! </p>" ; } //make sure search keyword is at least 2 characters. (buggy if not) if(strlen($trimmed) < 2){ $resulterror = "<p>Search Error</p><p>Your keyword has to be at least two characters long! </p>" ; } /*CREATE SEARCH FORM --------------------------*/ $search_form = '<form class="search-form" action="'.$currentFile.'" method="GET"> <div> <input name="q" type="text" value="'.$q.'"><input name="search" type="submit" value="Search"> </div> </form>'; /*DISPLAY QUERY ERRORS OR DO THE SEARCH --------------------------------------------*/ if($resulterror){ $resultmsg = $resulterror; }else{ // Build SQL Query for each keyword entered foreach ($trimmed_array as $trimm){ // MySQL "MATCH" is used for full-text searching. Please visit mysql for details. $query = "SELECT *, MATCH (".$title_field.",".$content_field.") AGAINST ('".$trimm."') AS score FROM ".$db_table." WHERE MATCH (".$title_field.",".$content_field.") AGAINST ('+".$trimm."' IN BOOLEAN MODE) HAVING score > 0.01 ORDER BY score DESC"; // Execute the query to get number of rows that contain search kewords $numresults=mysql_query ($query) or die ("Error in query: $query. " . mysql_error()); $row_num_links_main =mysql_num_rows ($numresults); //If MATCH query doesn't return any results due to how it works do a search using LIKE if($row_num_links_main < 1){ $query = "SELECT * FROM ".$db_table." WHERE ".$title_field." LIKE '%".$trimm."%' OR ".$content_field." LIKE '%".$trimm."%' ORDER BY ".$row_id." DESC" ; $numresults=mysql_query ($query); $row_num_links_main =mysql_num_rows ($numresults); } // next determine if 's' has been passed to script, if not use 0. // 's' is a variable that gets set as we navigate the search result pages. if (empty($s)) { $s=0; } // now let's get results. $query .= " LIMIT $s,$limit" ; $numresults = mysql_query ($query) or die ("Error in query: $query. " . mysql_error()); $row= mysql_fetch_array ($numresults); //store record id of every item that contains the keyword in the array we need to do this to avoid display of duplicate search result. do{ $adid_array[] = $row[ 'news_id' ]; }while( $row= mysql_fetch_array($numresults)); } //end foreach /*Display a message if no results found --------------------------*/ if($row_num_links_main == 0 && $row_num_links_main1 == 0){ $resultmsg = "<p>Search results for: ". $trimmed."</p><p>Sorry, your search returned zero results</p>" ; } //delete duplicate record id's from the array. To do this we will use array_unique function $tmparr = array_unique($adid_array); $i=0; foreach ($tmparr as $v) { $newarr[$i] = $v; $i++; } //total number of results $row_num_links_main = $row_num_links_main + $row_num_links_main1; if($resultmsg != ""){ $resultmsg = "<p>Search results for: <strong>" . $var."</strong></p>"; } /* FETCH RESULTS BASED ON THE ID --------------------------------------------*/ foreach($newarr as $value){ // EDIT HERE and specify your table and field unique ID for the SQL query $query_value = "SELECT * FROM ".$db_table." WHERE ".$row_id." = '".$value."'"; $num_value=mysql_query ($query_value); $row_linkcat= mysql_fetch_array ($num_value); $row_num_links= mysql_num_rows ($num_value); //create summary of the long text. For example if the field2 is your full text grab only first 130 characters of it for the result $introcontent = strip_tags($row_linkcat[$content_field]); $introcontent = substr($introcontent, 0, 130)."..."; //now let's make the keywods bold. To do that we will use preg_replace function. //Replace field $title = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $row_linkcat[ $title_field] ); $desc = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $introcontent); //COMMENT OUT THIS LINE: If using database ID field to drive links $link = preg_replace ( "'($var)'si" , "<strong>\\1</strong>" , $row_linkcat[$link_field] ); //UNCOMMENT and EDIT THIS LINE: If using database ID field to drive links //$link = 'http://yourdomain.com/pageid='. $row_linkcat[$link_field]; foreach($trimmed_array as $trimm){ if($trimm != 'b' ){ $title = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $title); $desc = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $desc); $link = preg_replace( "'($trimm)'si" , "<strong>\\1</strong>" , $link); }//end highlight }//end foreach $trimmed_array //format and display search results $resultmsg.= '<div class="search-result">'; $resultmsg.= '<div class="search-title"><a href="'.$link.'">'.$title.'</a></div>'; $resultmsg.= '<div class="search-text">'; $resultmsg.= $desc; $resultmsg.= '</div>'; $resultmsg.= '<a href="'.$link.'" class="search-link">'; $resultmsg.= $link; $resultmsg.= '</a>'; $resultmsg.= '</div>'; } //end foreach $newarr /* CREATE PAGINATION --------------------------------------------*/ if($row_num_links_main > $limit){ // next we need to do the links to other search result pages if ($s >=1) { // do not display previous link if 's' is '0' $prevs=($s-$limit); $resultmsg.= '<div class="search-previous"><a href="'.$PHP_SELF.'?s='.$prevs.'&q='.$var.'">Previous</a></div>'; } // check to see if last page $slimit =$s+$limit; if (!($slimit >= $row_num_links_main) && $row_num_links_main!=1) { // not last page so display next link $n=$s+$limit; $resultmsg.= '<div class="search-next"><a href="'.$PHP_SELF.'?s='.$n.'&q='.$var.'">Next</a></div>'; } }//end if $row_num_links_main > $limit }//end if no errors ?> <?php //display form echo $search_form; //display results echo $resultmsg; ?> I know that this might be asking a lot, but can someone who is smarter than me please give me instructions on how to set this up. I am at a complete loss. I've tried everything. I can connect to the db, and all, but it returns errors, and or blank screens. I will owe everyone. Thank you. I wonder whether someone may be able to help me please. I'm trying to put together php code and an html form that allows an administrator to search for a user via the email address, retrieving the 'first' and 'surname' from the pertinent record in a mySQL database. What I would like to happen is for the retrieved 'first' and surname' values to be automatically populated into the 'first' and 'surname' text boxes on the same search form. I can perform the search and retrieval of the correct record without any problem, but I can't work out how to populate the 'first' and 'surname' values into my search form. I am quote a novice with PHP so apologies if this is a really daft question, but I just windered whether somone could take a look at my code below and let me know where I've gone wrong? Many thanks PHP CODE Code: [Select] <?php require("phpfile.php"); // Opens a connection to a MySQL server $connection=mysql_connect ("hostname", $username, $password); if (!$connection) { die('Not connected : ' . mysql_error());} // Set the active MySQL database $db_selected = mysql_select_db($database, $connection); if (!$db_selected) { die ('Can\'t use db : ' . mysql_error()); } $email = $_POST['email']; $result = mysql_query("SELECT * FROM userdetails WHERE emailaddress like '%$email%'"); while($row = mysql_fetch_array($result)) { echo $row['forename']; echo $row['surname']; echo "<br />"; } ?> HTML FORM Code: [Select] !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Maptitle> <script src="js/gen_validatorv4.js" type="text/javascript"></script> </head> <h1><span class="blue">Sign Up</span> For Map My Finds</h1> <form name="userpasswordreset" id="userpasswordreset" method="post" action="search.php"> <h2>Your Details </h2> </div> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="26%" height="25"><strong>Email Address</strong></td> <td width="4%"> </td> <td width="70%"><input name="email" type="email" id="email" size="50" /></td> </tr> <tr> <td height="25"><strong>Confirm Email</strong></td> <td> </td> <td><input name="conf_email" type="email" id="conf_email" size="50" /></td> </tr> <tr> <td height="25"><label> <input type="submit" name="Submit" value="Search" /> </label></td> <td> </td> <td> </td> </tr> <tr> <td height="25"><strong> First Name </strong></td> <td> </td> <td><input name="fname" type="text" id="fname" size="30" value="<?php echo $forename; ?>" /></td> </tr> <tr> <td height="25"><strong> Address Last Name </strong></td> <td> </td> <td><input name="lname" type="text" id="lname" size="30" value="<?php echo $surname; ?>" /></td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> <tr> <td height="25"><strong>Password</strong></td> <td> </td> <td><input name="pass" type="password" id="pass" size="30" /></td> </tr> <tr> <td height="25"><strong>Confirm Password </strong></td> <td> </td> <td><input name="conf_pass" type="password" id="conf_pass" size="30" /></td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> <tr> <td height="25"><strong>Password Hint </strong></td> <td> </td> <td><input name="hint" type="text" id="hint" size="30" /></td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> <tr> <td height="25"> </td> <td> </td> <td> </td> </tr> </table> </form> <script language="JavaScript" type="text/javascript"> // Code for validating the form // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml // for details var frmvalidator = new Validator("userpasswordreset"); frmvalidator.addValidation("email","req","Please provide your email address"); frmvalidator.addValidation("email","email","Please enter a valid email address"); frmvalidator.addValidation("conf_email","eqelmnt=email", "The confirmed email address is not the same as the email address"); </body> </html> Hello I wonder if it is possible to make a search form with different fields where all conditions should be met if the field is set. I have this code: $sel = "SELECT * FROM database "; $sel .= "WHERE ((test1 = '$test1' "; $sel .= "AND test2 = '$test2' "; $sel .= "AND test3 = '$test3' "; $sel .= "ORDER BY id "; $query = mysql_query($sel) or die(mysql_error()); if (mysql_num_rows($query) == 0){ echo ("No result"); exit; When I use this and leave for example 1 field empty I get the error: No result. Is it possible to make smothing so the condition only should be met if the field is set? So If test1 and test3 are set these condition should be met.. I hope you can help! Thanks in advance! - Frederik Hello friends,
I am a novice in php. Though I create 2 scripts:
1. students registration form
2. search students by Registration Number
Our students' Registration Numbers are as follows: nifeA001, nifeA002 & so on...
But when someone enter just "nife" or "n" or "A" etc all the students's data is showing.
I want that students can search data by entering only Full Registration Number not a Part.
I am placing the search.php code below. Please help me out....
----------------- Search.php ------------------
<?php
mysql_connect("localhost", "root", "") or die("could not connect");
mysql_select_db("student") or die("could not connect");
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
//here
$query = mysql_query("SELECT * FROM user WHERE registration LIKE '%$searchq%'") or die("could not search!");
$count = mysql_num_rows($query);
if($count == 0){
$output = 'There was no search results!';
}else{
while($row = mysql_fetch_array($query)) {
$fname = $row['firstname'];
$lname = $row['surname'];
$id = $row['registration'];
$output .= '<div> '.$id.' '.$fname.' '.$lname.'</div>';
}
}
}
?>
<html>
<head>
</head>
<body>
<form action="form.php" method="post">
<input type="text" name="search" placeholder="search for students.."
<input type="submit" value=">>" />
</form>
<?php print("$output");?>
</body>
</html>
Edited by NasimUddinAhmmad, 13 January 2015 - 05:43 AM. I found an article on how to implement a mysql search (http://www.iamcal.com/publish/articles/php/search/) and it seemed like a good way to go, but I can't get it up and running. Here is my code: Code: [Select] <?php $db_host = 'localhost'; $db_user = 'username'; $db_pwd = 'password'; $database = 'dbname'; $table = 'Principals'; if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); $searchterms = 'dorr oliver'; function search_split_terms($terms){ $terms = preg_replace("/\"(.*?)\"/e", "search_transform_term('\$1')", $terms); $terms = preg_split("/\s+|,/", $terms); $out = array(); foreach($terms as $term){ $term = preg_replace("/\{WHITESPACE-([0-9]+)\}/e", "chr(\$1)", $term); $term = preg_replace("/\{COMMA\}/", ",", $term); $out[] = $term; } return $out; } function search_transform_term($term){ $term = preg_replace("/(\s)/e", "'{WHITESPACE-'.ord('\$1').'}'", $term); $term = preg_replace("/,/", "{COMMA}", $term); return $term; } function search_escape_rlike($string){ return preg_replace("/([.\[\]*^\$])/", '\\\$1', $string); } function search_db_escape_terms($terms){ $out = array(); foreach($terms as $term){ $out[] = '[[:<:]]'.AddSlashes(search_escape_rlike($term)).'[[:>:]]'; } return $out; } function search_perform($terms){ $terms = search_split_terms($terms); $terms_db = search_db_escape_terms($terms); $terms_rx = search_rx_escape_terms($terms); $parts = array(); foreach($terms_db as $term_db){ $parts[] = "Principals RLIKE '$term_db'"; } $parts = implode(' OR ', $parts); $sql = "SELECT * FROM Principal WHERE $parts"; $rows = array(); $result = mysql_query($sql); while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ $row[score] = 0; foreach($terms_rx as $term_rx){ $row[score] += preg_match_all("/$term_rx/i", $row[Principals], $null); } $rows[] = $row; } uasort($rows, 'search_sort_results'); return $rows; } function search_rx_escape_terms($terms){ $out = array(); foreach($terms as $term){ $out[] = '\b'.preg_quote($term, '/').'\b'; } return $out; } function search_sort_results($a, $b){ $ax = $a[score]; $bx = $b[score]; if ($ax == $bx){ return 0; } return ($ax > $bx) ? -1 : 1; } function search_html_escape_terms($terms){ $out = array(); foreach($terms as $term){ if (preg_match("/\s|,/", $term)){ $out[] = '"'.HtmlSpecialChars($term).'"'; }else{ $out[] = HtmlSpecialChars($term); } } return $out; } function search_pretty_terms($terms_html){ if (count($terms_html) == 1){ return array_pop($terms_html); } $last = array_pop($terms_html); return implode(', ', $terms_html)." and $last"; } # # do the search here... # $results = search_perform($searchterms); $term_list = search_pretty_terms(search_html_escape_terms(search_split_terms($searchterms))); The table name is 'Principals' and the field name I am trying to search is 'Principal'. I am getting an error on the line: while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ The error is: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource Can anyone shed some light on this for me? |