PHP - Adding A Search Mysql To Current Code
Hi.
I currently have php java to get my database results and limit the amount of data shown by a given value. The js includes buttons to go forward or backward in the database. Everything is all fine and dandy except I'm trying to add a very simple search for the user as well. I want the user to be able to select either "firstname" or "lastname" to search through the database and display the resulting rows based of the first three characters entered into the search criteria. I'm not sure where to start on this... Do I have to add something the js (I'm not very familiar with js), or should I add mysql_query's in the php linked file? Current Page Code: Link To Current Page Test Code: [Select] <!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> <title>Ness Physiotherapy and Sports Injury Clinic Web site - Site Map</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="description" content="Ness Physiotherapy and Sports Injury Clinic Our mission is to provide quality, evidenced based service in a safe, friendly, professional environment." /> <meta name="keywords" content="pain,rehabilitation,rehab,exercise,manipulation,musculoskeletal,pain,management,massage therapy,physiotherapy,sports injury,injury,injured,chronic pain,quality care,quality life,muscle balance,spinal fitness assessment, BMR PT, CAFCI, RMT" /> <!--Ness Physiotherapy and Sports Injury Clinic is owned by Sean Springer, Tamara Silvari and Charles Dirks. --> <meta name="language" content="EN" /> <meta name="copyright" content="Ness Physiotherapy and Sports Injury Clinic" /> <meta name="robots" content="ALL" /> <meta name="document-classification" content="Health" /> <meta name="document-classification" content="Health" /> <meta name="document-rights" content="Copyrighted Work" /> <meta name="document-type" content="Public" /> <meta name="document-rating" content="General" /> <meta name="document-distribution" content="Global" /> <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" /> <script type="text/javascript" src="../scripts/preloadimages.js"></script> <script type="text/javascript" src="../scripts/p7exp.js"></script> <script type="text/javascript" src="../scripts/formajax.js"></script> <!--[if lte IE 7]> <style> #menuwrapper, #p7menubar ul a {height: 1%;} a:active {width: auto;} </style> <![endif]--> <!--[if IE 5]> <style type="text/css"> /* place css box model fixes for IE 5* in this conditional comment */ .twoColFixRtHdr #sidebar1 { width: 220px; } </style> <![endif][if IE]> <style type="text/css"> /* place css fixes for all versions of IE in this conditional comment */ .twoColFixRtHdr #sidebar1 { padding-top: 30px; } .twoColFixRtHdr #mainContent { zoom: 1; } /* the above proprietary zoom property gives IE the hasLayout it needs to avoid several bugs */ </style> <![endif]--> <link href="../css/p7exp.css" rel="stylesheet" type="text/css" /> <link href="../css/basiclayout.css" rel="stylesheet" type="text/css" /> <link href="../css/general.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="../css/form_member_admin.css"/> </head> <body class="twoColFixRtHdr" onload="ajaxFunction('fw')"> <div id="container2"> <!-- Header Secion edit header.php if needed--> <?php require("../header.php"); ?> <div id="BasCon"> <form id="myForm" action="ajaxFunction(this.form); return false"> <div> <input type="hidden" name="st" value="0" > </input> </div> <table id="tbl_search"> <tr> <td colspan="5"><b>MEMBER LIST</b></td> </tr> <tr> <td><input type="button" id="back" value="Prev" onclick="ajaxFunction('bk'); return false" /></td> <td align="right"><input type="button" value="Next" id="fwd" onclick="ajaxFunction('fw'); return false" /></td> </tr> <tr> <td colspan="2"><div id="txtHint"><b>Records will be displayed here</b></div></td> </tr> </table> <div class="formdiv"> <label for="searchby">Search By:</label> <?php //get databast access file require "../dbConfigtest.php"; $query = "SELECT firstname,lastname FROM $usertable"; $result = mysql_query($query) or die(mysql_error()); ?> <select size="1" name="searchby" class="searchby"> <?php $i = 0; while ($i < mysql_num_fields($result)){ $fieldname = mysql_field_name($result, $i); echo '<option value="'.$fieldname.'">'.$fieldname.'</option>'; $i++; } ?> </select> <label for="newsearch">Search Value:</label> <input name='newsearch' type='text' value='' maxlength="32" /> <p> </p> <input class="button" type="submit" value="Search" name="search" /> </div><!--End Div formdiv--> <p> </p> <p> </p> </form> </div> <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats --> <br class="clearfloat" /> <div id="footer_abv_2"></div> <!-- end #footer abv --> <!-- Footer Secion edit footer.php if needed--> <?php require("../footer.php"); ?> </div> <!-- end #container2 --> </body> </html> PHP Code from "pagelisting.php" which is called from the java. <? //get databast access file include "../dbConfigtest.php"; //////////////////////////////// Main Code sarts ///////////////////////////////////////////// $endrecord=$_GET['endrecord'];// To take care global variable if OFF if(strlen($endrecord) > 0 and !is_numeric($endrecord)){ echo "Data Error"; exit; } $limit=25;// Number of records per page $nume=mysql_num_rows(mysql_query("select * from $usertable")); //echo "endrecord=$endrecord limit=$limit "; if($endrecord < $limit) {$endrecord = 0;} switch($_GET['direction']) { case "fw": $eu = $endrecord ; break; case "bk": $eu = $endrecord - 2*$limit; break; default: echo "Data Error"; exit; break; } if($eu < 0){$eu=0;} $endrecord =$eu+$limit; $t=mysql_query("select * from $usertable limit $eu,$limit"); $str= "{ \"data\" : ["; while($nt=mysql_fetch_array($t)){ $str=$str."{\"id\" : \"$nt[id]\", \"firstname\" : \"$nt[firstname]\", \"lastname\" : \"$nt[lastname]\", \"email\" : \"$nt[email]\", \"enewsletter\" : \"$nt[enewsletter]\"},"; //$str=$str."{\"myclass\" : \"$nt[class]\"},"; } $str=substr($str,0,(strLen($str)-1)); if(($endrecord) < $nume ){$end="yes";} else{$end="no";} if(($endrecord) > $limit ){$startrecord="yes";} else{$startrecord="no";} $str=$str."],\"value\" : [{\"endrecord\" : $endrecord,\"limit\" : $limit,\"end\" : \"$end\",\"startrecord\" : \"$startrecord\"}]}"; echo $str; //echo json_encode($str); ///////////////////////////////////////////////////////////////////////////////////////////// ?> Current js Code: Code: [Select] function ajaxFunction(val) { //document.writeln(val) var httpxml; try { // Firefox, Opera 8.0+, Safari httpxml=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { httpxml=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httpxml=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } function stateChanged() { if(httpxml.readyState==4) { var myObject = eval('(' + httpxml.responseText + ')'); var str="<table><tr><th>LINK</th><th>ID</th><th>FirstName</th><th>LastName</th><th>Email</th></tr>"; for(i=0;i<myObject.data.length;i++) { //var sPath = window.location.pathname; //var sPath = sPath.substring(sPath.lastIndexOf('/') + 1); var sPath = "testing/member_update_test.php"; var site_link = "www.nessphysiotherapy.com/"; var urlLink = site_link + sPath + "?id=" + myObject.data[i].id; var site_title = "EDIT"; str = str + "<tr><td>" + "<a href=\"http:\/\/" + urlLink + "\" title=\"site_title\">" +site_title + "<\/a>" + "<td>" + myObject.data[i].id + "</td><td>" + myObject.data[i].firstname + "</td><td>" + myObject.data[i].lastname + "</td><td>" + myObject.data[i].email + "</td></tr>" } var endrecord=myObject.value[0].endrecord document.forms.myForm.st.value=endrecord; if(myObject.value[0].end =="yes"){ document.getElementById("fwd").style.display='inline'; }else{document.getElementById("fwd").style.display='none';} if(myObject.value[0].startrecord =="yes"){ document.getElementById("back").style.display='inline'; }else{document.getElementById("back").style.display='none';} str = str + "</table>" document.getElementById("txtHint").innerHTML=str; } } var url="../scripts/pagelisting.php"; var myendrecord=document.forms.myForm.st.value; url=url+"?endrecord="+myendrecord; url=url+"&direction="+val; url=url+"&sid="+Math.random(); //alert(url) httpxml.onreadystatechange=stateChanged; httpxml.open("GET",url,true); httpxml.send(null); document.getElementById("txtHint").innerHTML="Please Wait...."; } Similar TutorialsFollowing from my previous post, i have a questionnaire and within each question it has the options to pick from raddio button (strongly agree, agree, disagree, N/A). For each value of each question i want to pass it into the relevant Field in my database but rather than overwriting the current value i want to be added on to it. (For example if the current value is 2, once the new value (1) has added it will make the new value of 3.). All I am trying to do is add a record on a page without the page refreshing. For that ajax is used. Here is the code.
It does not add the record to mysql table. Can anyone tell me what I am doing wrong?
record.php
<!DOCTYPE HTML> <html lang="en"> <head> <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script> <script type="text/javascript" > $(function() { $(".submit_button").click(function() { var textcontent = $("#content").val(); var name = $("#name").val(); var dataString = 'content='+ textcontent + '&name='+name; if(textcontent=='') { alert("Enter some text.."); $("#content").focus(); } else { $("#flash").show(); $("#flash").fadeIn(400).html('<span class="load">Loading..</span>'); $.ajax({ type: "POST", url: "action.php", data: dataString, cache: true, success: function(html){ $("#show").after(html); document.getElementById('content').value=''; $("#flash").hide(); $("#content").focus(); } }); } return false; }); }); </script> </head> <body> <?php $record_id = $_GET['id']; // getting ID of current page record ?> <form action="" method="post" enctype="multipart/form-data"> <div class="field"> <label for="title">Name *</label> <input type="text" name="name" id="name" value="" maxlength="20" placeholder="Your name"> </div> <div class="field"> <label for="content">content *</label> <textarea id="content" name="content" maxlength="500" placeholder="Details..."></textarea> </div> <input type="submit" name="submit" value="submit" class="submit_button"> </form> <div id="flash"></div> <div id="show"></div> </body> </html>action.php if(isset($_POST['submit'])) { if(empty($_POST['name']) || empty($_POST['content'])) { $error = 'Please fill in the required fields!'; } else { try { $name = trim($_POST['name']); $content = trim($_POST['content']); $stmt = $db->prepare("INSERT INTO records(record_id, name, content) VALUES(:recordid, :name, :content"); $stmt->execute(array( 'recordid' => $record_id, 'name' => $name, 'content' => $content )); if(!$stmt){ $error = 'Please fill in the required fields.'; } else { $success = 'Your post has been submitted.'; } } catch(Exception $e) { die($e->getMessage()); } } } I'm trying to do something that I thought was very simple about 2 weeks ago :-( I want to put a form on my site and link it to a database so when a user types a surname into the form they can search the db and the page will only display the surnames that match the search criteria. I got the db set up using phpmyadmin in about 2 minutes flat, but keep getting error messages when I write the php. I'm currently working with the below script, which keeps giving me the error 'unexpected T_string' on line 176 I've searched every forum and help site I can find, and the mysql and php manuals are just mind-boggling. I'm sure I'm making some really amateur mistake, but I'd really appreciate help with this! thanks all! <html> <head> <title>SEARCH RECORDS</title> </head> <body> <FORM NAME ="Search" METHOD ="POST" ACTION = "test3"> <INPUT TYPE = "TEXT" VALUE ="surname" NAME = "surname"> <INPUT TYPE = "Submit" Name = "Search" VALUE = "Search"> </FORM> </body> </html> <? $user_name = "*****"; $password = "*****"; $database = "*****"; $server = "localhost"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "SELECT * FROM *****" WHERE surname=$_POST['surname']; $result = mysql_query($SQL); while ($db_field = mysql_fetch_assoc($result)) { print $db_field['Grave'] . "<BR>"; print $db_field['Surname'] . "<BR>"; print $db_field['Forenames'] . "<BR>"; print $db_field['Death_Date'] . "<BR>"; print $db_field['Birth_Year'] . "<BR>"; } mysql_close($db_handle); } else { print "Database NOT Found "; mysql_close($db_handle); } ?> Ok, I have a variable ($incubation) set as 04:00:00. Then I have another variable ($starttime) set to the current time. Both are printing out fine. But I'm trying to get an $endtime from adding the incubation time to the start time. Code: [Select] $incubation = $row['incubation']; //IM GRABBING THIS TIME FROM THE DATABASE. It prints 04:00:00 $starttime = date("H:i:s"); //prints 16:23:39 $endtime = date("H:i:s", $starttime+$incubation); //prints 20:00:00 when it's suppose to print 20:23:39 Hi, I need to insert some code into my current form code which will check to see if a username exist and if so will display an echo message. If it does not exist will post the form (assuming everything else is filled in correctly). I have tried some code in a few places but it doesn't work correctly as I get the username message exist no matter what. I think I am inserting the code into the wrong area, so need assistance as to how to incorporate the username check code. $sql="select * from Profile where username = '$username'; $result = mysql_query( $sql, $conn ) or die( "ERR: SQL 1" ); if(mysql_num_rows($result)!=0) { process form } else { echo "That username already exist!"; } the current code of the form <?PHP //session_start(); require_once "formvalidator.php"; $show_form=true; if (!isset($_POST['Submit'])) { $human_number1 = rand(1, 12); $human_number2 = rand(1, 38); $human_answer = $human_number1 + $human_number2; $_SESSION['check_answer'] = $human_answer; } if(isset($_POST['Submit'])) { if (!isset($_SESSION['check_answer'])) { echo "<p>Error: Answer session not set</p>"; } if($_POST['math'] != $_SESSION['check_answer']) { echo "<p>You did not pass the human check.</p>"; exit(); } $validator = new FormValidator(); $validator->addValidation("FirstName","req","Please fill in FirstName"); $validator->addValidation("LastName","req","Please fill in LastName"); $validator->addValidation("UserName","req","Please fill in UserName"); $validator->addValidation("Password","req","Please fill in a Password"); $validator->addValidation("Password2","req","Please re-enter your password"); $validator->addValidation("Password2","eqelmnt=Password","Your passwords do not match!"); $validator->addValidation("email","email","The input for Email should be a valid email value"); $validator->addValidation("email","req","Please fill in Email"); $validator->addValidation("Zip","req","Please fill in your Zip Code"); $validator->addValidation("Security","req","Please fill in your Security Question"); $validator->addValidation("Security2","req","Please fill in your Security Answer"); if($validator->ValidateForm()) { $con = mysql_connect("localhost","uname","pw") or die('Could not connect: ' . mysql_error()); mysql_select_db("beatthis_beatthis") or die(mysql_error()); $FirstName=mysql_real_escape_string($_POST['FirstName']); //This value has to be the same as in the HTML form file $LastName=mysql_real_escape_string($_POST['LastName']); //This value has to be the same as in the HTML form file $UserName=mysql_real_escape_string($_POST['UserName']); //This value has to be the same as in the HTML form file $Password= md5($_POST['Password']); //This value has to be the same as in the HTML form file $Password2= md5($_POST['Password2']); //This value has to be the same as in the HTML form file $email=mysql_real_escape_string($_POST['email']); //This value has to be the same as in the HTML form file $Zip=mysql_real_escape_string($_POST['Zip']); //This value has to be the same as in the HTML form file $Birthday=mysql_real_escape_string($_POST['Birthday']); //This value has to be the same as in the HTML form file $Security=mysql_real_escape_string($_POST['Security']); //This value has to be the same as in the HTML form file $Security2=mysql_real_escape_string($_POST['Security2']); //This value has to be the same as in the HTML form file $sql="INSERT INTO Profile (`FirstName`,`LastName`,`Username`,`Password`,`Password2`,`email`,`Zip`,`Birthday`,`Security`,`Security2`) VALUES ('$FirstName','$LastName','$UserName','$Password','$Password2','$email','$Zip','$Birthday','$Security','$Security2')"; //echo $sql; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } else{ mail('email@gmail.com','A profile has been submitted!',$FirstName.' has submitted their profile',$body); echo "<h3>Your profile information has been submitted successfully.</h3>"; } mysql_close($con); $show_form=false; } else { echo "<h3 class='ErrorTitle'>Validation Errors:</h3>"; $error_hash = $validator->GetErrors(); foreach($error_hash as $inpname => $inp_err) { echo "<p class='errors'>$inpname : $inp_err</p>\n"; } } } if(true == $show_form) { ?> 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 I have code to search a database of members, I can search by lastname but having a little problem. I want to be able to search by lastname starting with the first letter. (ie: a or b or c or d and so on). As it is right now I can only search by first letter of last name if I add % to the search (ie: a% b% c%) will give me all members with the last names starting with the approiate letter designation. I'm not sure how to handle this, any help would be appreciated. Thanks. Code: [Select] <!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=utf-8" /> <title></title> </head> <body> <center><table cellspacing="10" cellpadding="10" width="750" border="0"> <h4>Search</h4> <form name="search" method="post" action="<?php $PHP_SELF?>"> Seach for: <input type="text" name="find" /> in <Select NAME="field"> <Option VALUE="lname">Last Name</option> <input type="hidden" name="searching" value="yes" /> <input type="submit" name="search" value="Search" /> </form> <?php // check to see if anything is posted if (isset($_POST['find'])) {$find = $_POST['find'];} if (isset($_POST['searching'])) {$searching = $_POST['searching'];} if (isset($_POST['field'])) {$field = $_POST['field'];} //This is only displayed if they have submitted the form if (isset($searching) && $searching=="yes") { echo "<h4>Results</h4><p>"; // If they did not enter a search term we give them an error if (empty($find)) { echo "<p>You forgot to enter a search term"; exit; } // Otherwise we connect to our Database mysql_connect("localhost", "root", "1910") or die(mysql_error()); mysql_select_db("cmc_member") or die(mysql_error()); // We preform a bit of filtering $find = strtoupper($find); $find = strip_tags($find); $find = trim ($find); // Now we search for our search term, in the field the user specified $results = mysql_query("SELECT * FROM members WHERE upper($field) LIKE'$find'"); // And we display the results if($results && mysql_num_rows($results) > 0) { $i = 0; $max_columns = 3; while($row = mysql_fetch_array($results)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; // make sure we have a valid product ALIGN='CENTER' if($fname != "" && $fname != null) echo "<td ALIGN='CENTER'><FONT COLOR='red'><b>$fname $lname</b></FONT><br> $address <br> $city $state $zip <br>$phone<br><a href=\"mailto: $email\">$email</a><br></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 < $max_columns) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; } //This counts the number or results - and if there wasn't any it gives them a little message explaining that $anymatches = mysql_num_rows($results); if ($anymatches == 0) { echo "Sorry, but we can not find an entry to match your query<br><br>"; } //And we remind them what they searched for echo "<b>Searched For:</b> " .$find; } ?> </tr> </table></center> </body> </html> Code: [Select] $query = "INSERT INTO contactv3(name,email,msg) VALUES ('$name','$email','$msg')"; $result = mysql_query( $query ); if( !$result ) { die( mysql_error() ); } I have this current php snippet inserting the $name and $msg into a mysql db. $name and $msg come from here (a form that the user fills out). Code: [Select] <input type="text" size=28 name="name"> <input type="password" size=28 name="msg" > but is it possible to also enter the URL or perhaps a parameter that is appended to the end of the URL into the mysql db into separate column? if I'm outputting from mysql with this: Code: [Select] // Connects to your Database mysql_connect("localhost", "root", "") or die(mysql_error()) ; mysql_select_db("test") or die(mysql_error()) ; //Retrieves data from MySQL $data = mysql_query("SELECT * FROM tickets") or die(mysql_error()); //Puts it into an array while($info = mysql_fetch_array( $data )) { //Outputs the image and other data Echo "<b>asset number:</b> ".$info['AssetNumber'] . "<br> "; Echo "<b>subject:</b> ".$info['subject'] . " <br>"; Echo "<b>notes:</b> ".$info['Notes'] . " <hr>"; } can I base the record it outputs somehow on this: Code: [Select] $value=""; $value = ProcessLargeText(GetData($data,"Asset Number", ""),"","",MODE_VIEW); if($mainTableOwnerID=="Asset Number") $ownerIdValue=$value; $xt->assign("Asset_Number_value",$value); if(!$pageObject->isAppearOnTabs("Asset Number")) $xt->assign("Asset_Number_fieldblock",true); else $xt->assign("Asset_Number_tabfieldblock",true); It's kind of like a job history so its getting records of job history from one table while the second piece of code is getting the asset details from a main table Hi there, I've just started learning php and mysql today. I'm putting things together in dreamweaver and everything is running smoothly (ish). I've got a form written in php that sends data to a database. All fine. I need to send the time of submission to the database. I've put in a hidden field, what code should I use to set the field value to a mysql field of type DATETIME? Cheers. Hi I have a custom built website with 40 pages or so that I am working on. Its all PHP based. However it is not on a CMS, it was a static HTML site converted into php with a bunch of include files etc now. I am keen to add a search facility, however I have no idea how to go about this. I know there are 3rd party paid offerings from Google, but I was wondering if anyone can advise me if its easy to setup without having to pay a 3rd party? Any advice is greatly appreciated. I added a search form on my site but I cannot figure out how to add links to the search results.
The results are being posted as the item name and the item pages look like this used-product.php?Item=102
I am not understanding how I can have that url match up with my item name.
Here is my results.php code
In the header
<?php include_once('mysql_connect.php'); if (!isset($_POST['search'])) { header ("Location:index.php"); } $search_sql="SELECT * FROM new_equip WHERE itemname LIKE '% " .$_POST ['search'] . " %'"; $search_query=mysql_query($search_sql); if(mysql_num_rows($search_query)!=0) { $search_rs=mysql_fetch_assoc($search_query); } ?>and where the results are being displayed <?phpif (mysql_num_rows($search_query)!=0){ do {?> <p><a href="new-product.php?Item=<?php echo $eid; ?>"><?php echo $search_rs ['itemname']?></a></p> <?php } while ($search_rs=mysql_fetch_assoc($search_query)) ; } else { echo "No Results Found"; } ?>I have been on this and trying to figure out another issue I am having and I cannot figure out either of them. (The other is deleting a row from a table with the click of a link) Any help on this would be greatly appreciated it. I have looked and trial and error all day and I cannot seem to get it. Hi, I have some code which displays my blog post in a foreach loop, and I want to add some social sharing code(FB like button, share on Twitter etc.), but the problem is the way I have my code now, creates 3 instances of the sharing buttons, but if you like one post, all three are liked and any thing you do affects all of the blog post. How can I fix this? <?php include ("includes/includes.php"); $blogPosts = GetBlogPosts(); foreach ($blogPosts as $post) { echo "<div class='post'>"; echo "<h2>" . $post->title . "</h2>"; echo "<p class='postnote'>" . $post->post . "</p"; echo "<span class='footer'>Posted By: " . $post->author . "</span>"; echo "<span class='footer'>Posted On: " . $post->datePosted . "</span>"; echo "<span class='footer'>Tags: " . $post->tags . "</span>"; echo ' <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_counter addthis_pill_style"></a> </div> <script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=webguync"></script>'; echo "</div>"; } ?> i get this error Warning: current() [function.current]: Passed variable is not an array or object.. for this Code: [Select] $lastblock = current( ${"s".$row} ); print_r($lastblock); when i change to this it works.. Code: [Select] $lastblock = current( $s0 ); print_r($lastblock); The problem is i won't know the $row seeing as it is in a while loop. Solution? Hi, I'm wanting to find rows whose date is within the next week of the current month of the current year. The format of the date is, for example: 2010-10-28 Any ideas guys? Thanks lots! Hello - I've come to an issue with something I'm working on and have searched around with no luck. When editing user accounts I want it to not be able to change the e-mail address into existing ones on other rows, but when submitting the form it takes into account that this particular rows email address is the same as the one which was sent via $_POST and throws up the error. The desired behaviour I want is for it to ignore the ID of the row which was posted, but take into account every other row. Here's the code as it stands at the moment: $email = $_POST['email']; $checkemail = mysql_query("SELECT email FROM users WHERE email='$email'"); } if (mysql_num_rows($checkemail) > 0) { return $this->error("The e-mail address you provided is already associated with an account."); } hey everyone! in new to the whole php and mysql thing and i am stuck with one part, i have got a login script, once loged in it takes them to there account page, on there account page they can added data into there file, to mysql, so what I'm looking for is how to add the username they logged in with to be added into the database with the rest of the information they just submitted, so when they go to retrieve there information into a table they will only get the information that has there username with it. as much help as possible would be great! thank-you hello i am trying to add infomation into the mysql but it always seems to add it a 0 instead of what i am typeing into the form, the form is to add recipies to a users file. these are the scriprts, the fields that arnt showing up is prep and cook add_recipie.php <?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 objects before we can use them below in this script $activeLinkObject = new autoActiveLink; $myObject = new convertToAgo; ?> <?php // Include this script for random member display on home page include_once "scripts/homePage_randomMembers.php"; ?> <?php $sql_blabs = mysql_query("SELECT id, mem_id, the_blab, blab_date FROM blabbing ORDER BY blab_date DESC LIMIT 30"); $blabberDisplayList = ""; // Initialize the variable here while($row = mysql_fetch_array($sql_blabs)){ $blabid = $row["id"]; $uid = $row["mem_id"]; $the_blab = $row["the_blab"]; $notokinarray = array("fag", "gay", "shit", "fuck", "stupid", "idiot", "asshole", "cunt", "douche"); $okinarray = array("sorcerer", "grey", "shug", "farg", "smart", "awesome guy", "asshole", "cake", "dude"); $the_blab = str_replace($notokinarray, $okinarray, $the_blab); $the_blab = ($activeLinkObject -> makeActiveLink($the_blab)); $blab_date = $row["blab_date"]; $convertedTime = ($myObject -> convert_datetime($blab_date)); $whenBlab = ($myObject -> makeAgo($convertedTime)); //$blab_date = strftime("%b %d, %Y %I:%M:%S %p", strtotime($blab_date)); // Inner sql query $sql_mem_data = mysql_query("SELECT id, username, firstname, lastname FROM myMembers WHERE id='$uid' LIMIT 1"); while($row = mysql_fetch_array($sql_mem_data)){ $uid = $row["id"]; $username = $row["username"]; $firstname = $row["firstname"]; if ($firstname != "") {$username = $firstname; } // (I added usernames late in my system, this line is not needed for you) /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $ucheck_pic = "members/$uid/image01.jpg"; $udefault_pic = "members/0/image01.jpg"; if (file_exists($ucheck_pic)) { $blabber_pic = '<div style="overflow:hidden; width:40px; height:40px;"><img src="' . $ucheck_pic . '" width="40px" border="0" /></div>'; // forces picture to be 100px wide and no more } else { $blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" height=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more } $blabberDisplayList .= ' <table width="100%" align="center" cellpadding="4" bgcolor="#CCCCCC"> <tr> <td width="7%" bgcolor="#FFFFFF" valign="top"><a href="profile.php?id=' . $uid . '">' . $blabber_pic . '</a> </td> <td width="93%" bgcolor="#EFEFEF" style="line-height:1.5em;" valign="top"><span class="greenColor textsize10">' . $whenBlab . ' <a href="profile.php?id=' . $uid . '">' . $username . '</a> said: </span><br /> ' . $the_blab . '</td> </tr> </table>'; } } ?> <!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="Web Intersect is a deft combination of powerful free open source software for social networking, mixed with insider guidance and tutorials as to how it is made at its core for maximum adaptability. The goal is to give you a free website system that has a network or community integrated into it to allow people to join and interact with your website when you have the need." /> <meta name="Keywords" content="web intersect, how to build community, build social network, how to build website, learn free online, php and mysql, internet crossroads, directory, friend, business, update, profile, connect, all, website, blog, social network, connecting people, youtube, myspace, facebook, twitter, dynamic, portal, community, technical, expert, professional, personal, find, school, build, join, combine, marketing, optimization, spider, search, engine, seo, script" /> <title>CookBookers</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"> #Layer1 { height:210px; } body { background-color: #3c60a4; } .style4 {font-size: 36px} </style> </head> <body> <p> <?php include_once "header_template.php"; ?> </head> <body style="margin:0px;"> <center> </p> <p> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td width="124" valign="top"> <td width="776" colspan="2" align="left" valign="top" style="background-color:#EFEFEF; border:#999 0px; padding:10px;"> <table border="0" cellpadding="6"> </table> <table width="574" border="0"> <form method="POST" action="include/recipe.php"> <span class="style4">Add Recipie</span> <tr> <th width="232" scope="col"> </th> <th width="332" scope="col"> </th> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Public:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="Pub" value="1" type="checkbox" id="Pub"/> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Title:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="title" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Prep time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="prep" type="text" size="7" maxlength="10" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Cooking time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="cook" type="text" size="7" maxlength="10" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Makes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="make" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Ingrediants:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="ingr" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Method: </span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="desc" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Notes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="note" cols="40"></textarea> </span></td> </tr> <tr> <td><input name="submit" type="submit" style="padding:5px 10px;" value="Submit" /></td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> recipie.php <?php //include("session.php"); include("database.php"); @session_start(); $user = $_SESSION['username']; //die($user); $Pub=$_POST['Pub']; $title=$_POST['title']; $prep=$_POST['prep']; $cook=$_POST['cook']; $make=$_POST['make']; $ingr=$_POST['ingr']; $desc=$_POST['desc']; $note=$_POST['note']; //if($user=="Guest"||$user==""){ //header("Location: ../index.php"); //} //else{ $database->AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc,$note); header("Location: ../recipe_added.php"); //} ?> database.php <? /** * Database.php * * The Database class is meant to simplify the task of accessing * information from the website's database. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 17, 2004 */ include("constants.php"); class MySQLDB { var $connection; //The MySQL database connection var $num_active_users; //Number of active users viewing site var $num_active_guests; //Number of active guests viewing site var $num_members; //Number of signed-up users /* Note: call getNumMembers() to access $num_members! */ /* Class constructor */ function MySQLDB(){ /* Make connection to database */ $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error()); mysql_select_db(DB_NAME, $this->connection) or die(mysql_error()); /** * Only query database to find out number of members * when getNumMembers() is called for the first time, * until then, default value set. */ $this->num_members = -1; if(TRACK_VISITORS){ /* Calculate number of users at site */ $this->calcNumActiveUsers(); /* Calculate number of guests at site */ $this->calcNumActiveGuests(); } } /** * confirmUserPass - Checks whether or not the given * username is in the database, if so it checks if the * given password is the same password in the database * for that user. If the user doesn't exist or if the * passwords don't match up, it returns an error code * (1 or 2). On success it returns 0. */ function confirmUserPass($username, $password){ /* Add slashes if necessary (for query) */ if(!get_magic_quotes_gpc()) { $username = addslashes($username); } /* Verify that user is in database */ $q = "SELECT password FROM ".TBL_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); if(!$result || (mysql_numrows($result) < 1)){ return 1; //Indicates username failure } /* Retrieve password from result, strip slashes */ $dbarray = mysql_fetch_array($result); $dbarray['password'] = stripslashes($dbarray['password']); $password = stripslashes($password); /* Validate that password is correct */ if($password == $dbarray['password']){ return 0; //Success! Username and password confirmed } else{ return 2; //Indicates password failure } } /** * confirmUserID - Checks whether or not the given * username is in the database, if so it checks if the * given userid is the same userid in the database * for that user. If the user doesn't exist or if the * userids don't match up, it returns an error code * (1 or 2). On success it returns 0. */ function confirmUserID($username, $userid){ /* Add slashes if necessary (for query) */ if(!get_magic_quotes_gpc()) { $username = addslashes($username); } /* Verify that user is in database */ $q = "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); if(!$result || (mysql_numrows($result) < 1)){ return 1; //Indicates username failure } /* Retrieve userid from result, strip slashes */ $dbarray = mysql_fetch_array($result); $dbarray['userid'] = stripslashes($dbarray['userid']); $userid = stripslashes($userid); /* Validate that userid is correct */ if($userid == $dbarray['userid']){ return 0; //Success! Username and userid confirmed } else{ return 2; //Indicates userid invalid } } /** * usernameTaken - Returns true if the username has * been taken by another user, false otherwise. */ function usernameTaken($username){ if(!get_magic_quotes_gpc()){ $username = addslashes($username); } $q = "SELECT username FROM ".TBL_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); return (mysql_numrows($result) > 0); } function showRecipees($username){ $q = "SELECT * FROM recipies WHERE user = '$username'"; $result = mysql_query($q, $this->connection); /* Error occurred, return given name by default */ if(!$result || (mysql_numrows($result) < 1)){ return NULL; } /* Return result array */ $rows; $i=0; while($row=mysql_fetch_row($result)) { $rows[$i]=$row; $i++; } return $rows; } function showRecipees1(){ $q = "SELECT * FROM recipies"; $result = mysql_query($q, $this->connection); /* Error occurred, return given name by default */ if(!$result || (mysql_numrows($result) < 1)){ return NULL; } /* Return result array */ $rows; $i=0; while($row=mysql_fetch_row($result)) { $rows[$i]=$row; $i++; } return $rows; } /** * usernameBanned - Returns true if the username has * been banned by the administrator. */ function usernameBanned($username){ if(!get_magic_quotes_gpc()){ $username = addslashes($username); } $q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); return (mysql_numrows($result) > 0); } /** * addNewUser - Inserts the given (username, password, email) * info into the database. Appropriate user level is set. * Returns true on success, false otherwise. */ function addNewUser($username, $password, $email){ $time = time(); /* If admin sign up, give admin user level */ if(strcasecmp($username, ADMIN_NAME) == 0){ $ulevel = ADMIN_LEVEL; }else{ $ulevel = USER_LEVEL; } $q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', $time)"; return mysql_query($q, $this->connection); } /** * updateUserField - Updates a field, specified by the field * parameter, in the user's row of the database. */ function updateUserField($username, $field, $value){ $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'"; return mysql_query($q, $this->connection); } /** * getUserInfo - Returns the result array from a mysql * query asking for all information stored regarding * the given username. If query fails, NULL is returned. */ function getUserInfo($username){ $q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); /* Error occurred, return given name by default */ if(!$result || (mysql_numrows($result) < 1)){ return NULL; } /* Return result array */ $dbarray = mysql_fetch_array($result); return $dbarray; } /** * getNumMembers - Returns the number of signed-up users * of the website, banned members not included. The first * time the function is called on page load, the database * is queried, on subsequent calls, the stored result * is returned. This is to improve efficiency, effectively * not querying the database when no call is made. */ function getNumMembers(){ if($this->num_members < 0){ $q = "SELECT * FROM ".TBL_USERS; $result = mysql_query($q, $this->connection); $this->num_members = mysql_numrows($result); } return $this->num_members; } /** * calcNumActiveUsers - Finds out how many active users * are viewing site and sets class variable accordingly. */ function calcNumActiveUsers(){ /* Calculate number of users at site */ $q = "SELECT * FROM ".TBL_ACTIVE_USERS; $result = mysql_query($q, $this->connection); $this->num_active_users = mysql_numrows($result); } /** * calcNumActiveGuests - Finds out how many active guests * are viewing site and sets class variable accordingly. */ function calcNumActiveGuests(){ /* Calculate number of guests at site */ $q = "SELECT * FROM ".TBL_ACTIVE_GUESTS; $result = mysql_query($q, $this->connection); $this->num_active_guests = mysql_numrows($result); } /** * addActiveUser - Updates username's last active timestamp * in the database, and also adds him to the table of * active users, or updates timestamp if already there. */ function addActiveUser($username, $time){ $q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'"; mysql_query($q, $this->connection); if(!TRACK_VISITORS) return; $q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* addActiveGuest - Adds guest to active guests table */ function addActiveGuest($ip, $time){ if(!TRACK_VISITORS) return; $q = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } /* These functions are self explanatory, no need for comments */ /* removeActiveUser */ function removeActiveUser($username){ if(!TRACK_VISITORS) return; $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* removeActiveGuest */ function removeActiveGuest($ip){ if(!TRACK_VISITORS) return; $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } /* removeInactiveUsers */ function removeInactiveUsers(){ if(!TRACK_VISITORS) return; $timeout = time()-USER_TIMEOUT*60; $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* removeInactiveGuests */ function removeInactiveGuests(){ if(!TRACK_VISITORS) return; $timeout = time()-GUEST_TIMEOUT*60; $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } function AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc, $note){ if(!TRACK_VISITORS) return; $q = "INSERT INTO recipies (`user` ,`Pub` ,`title` ,`prep` ,`cook` ,`makes` ,`ingredients` ,`recipe` ,`notes`)VALUES ('$user', '$Pub', '$title', 'prep', 'cook','$make', '$ingr', '$desc', '$note');"; mysql_query($q, $this->connection) or die(mysql_error()); $this->calcNumActiveGuests(); } function recipie_comment($user,$comment,$recipie_id){ if(!TRACK_VISITORS) return; $q = "INSERT INTO recipie_comment (`user` ,`comment`, `recipie_id`);"; mysql_query($q, $this->connection) or die(mysql_error()); $this->calcNumActiveGuests(); } /** * query - Performs the given query on the database and * returns the result, which may be false, true or a * resource identifier. */ function query($query){ return mysql_query($query, $this->connection); } }; /* Create database connection */ $database = new MySQLDB; ?> and also the fields in the database are int 11 for both prep and cook thanks |