PHP - Help With Adding Checkbox Into Mysql
Hey Guys,
I'm really struggling to find whats wrong with this code. The form before submit has several checkboxes as part of an array which is below
The next page then goes to this and I get the error "Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /homepages/39/d837976904/htdocs/Scheduler/add_job3.php:10 Stack trace: #0 {main} thrown in /homepages/39/d837976904/htdocs/Scheduler/add_job3.php on line 10"
<?php $process = $_GET["process"];
include "Includes/config.php";
$checkBox = implode(',', $_POST['engineers']);
if(isset($_POST['submit'])) mysql_query($query1) or die (mysql_error() ); echo "Complete"; }
?> Can anyone help with the code please Similar TutorialsTrying to fix existing some code (complete beginner here) on the company I work for website. There's a check-box which when ticked should apply delivery charges and if not it shouldn't - currently it's working in that on the same page it calculates the total cost correctly when checked or not checked but when passing on information it always passes on the delivery charge even if un-ticked... The simplest thing I can see would be to put an if statement in to say if (not ticked) then del_charges = 0.00. Any idea how I can do this in this instance? Code: [Select] <?php // add a checkbox for delivery charges echo '<span class="form"><label>Delivery Charges</label>'; echo '<input type="checkbox" name="del_charges" id="del_charges" value="1" class="boxes" '; if ( isset($_POST['del_charges']) && !empty($_POST['del_charges']) ) echo 'checked="checked"'; echo '/>'; ?> Thanks. Hi all. I try to adding checkbox when I call my function, my Class code is Code: [Select] class SQLconn{ function fetchData($table_name, $argument, $linebreak, $end_linebreak){ $result = mysql_query("select * from $table_name where status='$argument'"); while($row=mysql_fetch_row($result)){ echo $linebreak.$row[1]."<input type='checkbox' name='option' id='checkbox' value=$row[0] />".$end_linebreak; //$row[0] is 'job_id' from database } } } and my view code is like this Code: [Select] <?php $connect = new SQLconn(config()); $connect->connectDB(); $connect->fetchData("todo", "Undone", "<li>", "</li>"); //this is where the problem is $connect->closeConn(); ?> With that code I succesfully achieve my goal to add checkbox with right 'job_id' value but this is a workaround and not good because if I code it this way my function will be broken if use it somewhere else. My question is, how can I fix my code so I can add checkbox to view page but I can keep my function clean? Really need opinion about this?? Hello, I have been spending over 6 hours trying to square this away and I have looked at some tutorials from PHPFreaks... Maybe I'm missing something. Basically I rebuilding the form from bottom up and I thought some check boxes would be easier for some part of the form instead of drop-down menu. Basically this form is submitting query to MySQL: article_add.php (Basically has the form) article_insert.php (Basically insert the data to MySQL) Here is one part of the form where the check box is located: Here is article_add.php <form action="article_insert.php" method="post"> <-- OTHER INPUT BOXES --> <div class="inputfieldtb"><label for="news_cat">News Categories:</label> <? echo "<table>"; echo "<tr>"; $counter = 1; while ($nc = mysql_fetch_array($news_cats)) { $ncat_id = $nc['ncat_id']; $ncat_name = $nc['ncat_label']; echo "<td><div><input type=\"checkbox\" name=\"category[]\" value=\"$ncat_id\" ''/>$ncat_name</div></td>\n"; if (($counter % 4) == 0) { echo "</tr><tr>"; } $counter ++; } echo "</tr></table>"; echo "<br />"; ?> </div> <-- MORE FORMS --> </form> Here is article_insert.php // CONNECT TO DATABASE include("../mods/connect.php"); <--- OTHER DATA INSERT IN MYSQL --> $news_cat = mysql_real_escape_string(implode(',', $_POST['category'])); // <-- Checkbox Data <--- MORE DATA INSERT IN MYSQL --> $query = "INSERT INTO news_articles VALUES ('<--- MORE CONTENT BEING INSERT INTO MYSQL -->,'$news_cat','$news_content',<--- MORE CONTENT BEING INSERT INTO MYSQL -->'')"; mysql_query($query) or die ('Error inserting new data into the data to the database: ' . mysql_error() . ''); The error I'm getting is "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '','','3','0','','','')' at line 1"; So what am I doing wrong? Once I get this resolved, I would like to learn how to display the checkbox / updated the checkbox as well. Thank you in advance for your time and your help with this problem. hello i need some help with my script and check boxes, i want it so if the user dosent click public it adds in the database 0 and public 1 i dont know how to submit that part, this is my script so far to add recipie <?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; } .style3 {font-size: 24px} body { background-color: #3c60a4; } </style> </head> <body> <p> <?php include_once "header_template.php"; ?> </head> <body style="margin:0px;"> <center> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td width="235" valign="top"> <td width="665" colspan="2" align="left" valign="top" style="background-color:#EFEFEF; border:#999 0px; padding:10px;"> <table border="0" cellpadding="6"> <tr> <td> <form method="POST" action="include/recipe.php"> <table cellpadding="0px" border="0" align="left" cellspacing="5px" style="font-size:14px;"> <tr> <td><span class="style3">Add New Recipie:</span><br /></td> <tr> <td><h4 style="margin-bottom:5px; color:brown;">Public: <input name="Pub" type="checkbox" id="Pub" value="checkbox" /> </h4> </td> </tr> <tr> <td><h4 style="margin-bottom:5px; color:brown;">Title: </h4> <input type="text" name="title"></td> </tr> <tr> <td><h4 style="margin-bottom:5px; color:brown;">Makes: </h4> <input type="text" name="make"></td> </tr> <tr> <td><h4 style="margin-bottom:5px; color:brown;">Ingrediants: </h4> <textarea rows="10" name="ingr" cols="40"></textarea><br></td> </tr> <tr> <td><h4 style="margin-bottom:5px; color:brown;">Method: </h4> <textarea rows="10" name="desc" cols="40"></textarea></td> </tr> <tr> <td><h4 style="margin-bottom:5px; color:brown;">Notes: </h4> <textarea rows="10" name="note" cols="40"></textarea></td> </tr> <tr> <td><input type="submit" value="Submit" style="padding:5px 10px;"></td> </tr> </table> </form> </td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> process the recipie <?php //include("session.php"); include("database.php"); @session_start(); $user = $_SESSION['username']; } //die($user); $pub=$_POST['pub']; $title=$_POST['title']; $make=$_POST['make']; $ingr=$_POST['ingr']; $desc=$_POST['desc']; $note=$_POST['note']; //if($user=="Guest"||$user==""){ //header("Location: ../index.php"); //} //else{ $database->AddRecipe($user,$title,$make,$ingr,$desc,$note); header("Location: ../add_recipie.php"); //} ?> anyones help would be appriceated thank-you Hi I have an array of checkboxes whose values if checked can be updated in mysql. The code I have below accomplishes that just fine. On my form I have: print "<form method='post' action='update.php'>\n"; /////// mysQL query here $myID = $itemRow['myID']; $chk = $itemRow['item_shipped'] == 1 ? 'checked' : ''; echo "<input type=checkbox name=cbox[] value='{$itemRow['myID']}' $chk>"; echo"</form>"; The above code displays various items with a checkbox next to them. So if that checkbox is checked the code below stores that in mysql. On my update.php page I have: if(sizeof($_POST['cbox'])) { //means if at least one check box is selected foreach($_POST['cbox'] AS $id) { mysql_query("UPDATE om SET item_shipped ='1' WHERE myID=$id"); } //end foreach } //end IF The problem is though i can check a checkbox and store that value '1' in mysql, I have no way of unchecking an already checked checkbox and storing the '0' in mysql. Can anyone help? Thanks in advance So first of all, I have a confession, I used Dreamweaver to take care of all my database work. Pheww. Now that I got that of my chest, I am having problems, not only with my lack of experience working with databases, but with my script also. I need to insert multiple checkbox values into my database into the same cell. So I have searched around and I thought I had found a fairly good approach, but with Dw's hodgepodge of overcomplicated mess, I am finding problems integrating it. The error I am getting post submission is "Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in C:\wamp\www\gov\ballot.php on line 10 Column 'involvement' cannot be null" So if you would, could you debug my script and give me some instruction along to way so that I can learn a little something too? Here is my script: <?php require_once('Connections/ballot.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "Ballot")) { $insertSQL = sprintf("INSERT INTO votes (`first`, `last`, gender, grade, involvement, schedule, party, `time`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['first'], "text"), GetSQLValueString($_POST['last'], "text"), GetSQLValueString($_POST['gender'], "text"), GetSQLValueString($_POST['grade'], "text"), GetSQLValueString($_POST['involvement'], "text"), GetSQLValueString($_POST['schedule'], "text"), GetSQLValueString($_POST['party'], "text"), GetSQLValueString($_POST['time'], "text")); mysql_select_db($database_ballot, $ballot); $Result1 = mysql_query($insertSQL, $ballot) or die(mysql_error()); $insertGoTo = "thanks.php"; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $insertGoTo)); } mysql_select_db($database_ballot, $ballot); $query_Recordset1 = "SELECT * FROM votes"; $Recordset1 = mysql_query($query_Recordset1, $ballot) or die(mysql_error()); $row_Recordset1 = mysql_fetch_assoc($Recordset1); $totalRows_Recordset1 = mysql_num_rows($Recordset1); ?> <!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>Please Place your Vote Below</title> </head> <body style="background-image:url(images/bg.jpg); background-repeat:repeat-x; background-color:#000000;"> <table align="center" bgcolor="#FFFFFF" cellpadding="0" cellspacing="0" border="0"> <tr><td> <div style="border:thin; border-color:000000; border-style:groove; width:700px; background-color:ffffff;"> <div align="center"><a href="index.php"><img src="images/header.jpg" alt="Mock Elections 2010" /></a></div> <div style="margin:10px; margin-top:30px;"> Before continuing to vote, in order to count your vote, we ask that you please ensure you are adhereing to the following guidelines: </div> <div style="margin:30px"> <p>- When putting your name, remember to put your full legal name. NO nicknames.<br /> - Be sure that all your information is valid otherwise your vote will not be counted. <br /> </p> </div> <div style="margin-left:150px; margin-right:150px; margin-top:50px;"> <form action="<?php echo $editFormAction; ?>" method="POST" name="Ballot"> First Name: <input type="text" name="first" /><br /> Last Name: <input type="text" name="last" /><br /> <div>Gender: <label> Male <input type="radio" value="Male" name="gender" /></label> <label>Female <input type="radio" value="Female" name="gender" /></label> </div> Grade: <select name="grade"> <option selected="selected"> </option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="Teacher">Teacher</option> <option value="Staff">Staff</option> </select><br /> <div>Involvement: <label> <input type="checkbox" name="involvement[]" value="Athletics" id="involvement_0" /> Athletics</label> <label> <input type="checkbox" name="involvement[]" value="Co-Curricular" id="involvement_1" /> Co-Curricular</label> <label> <input type="checkbox" name="involvement[]" value="Clubs" id="involvement_2" /> Clubs</label> </div> <div>Schedule: <label><input type="radio" value="C4" name="schedule" />C4</label> <label><input type="radio" value="All Day" name="schedule" />All Day Hauser Student</label> </div> <div>Party: <label><input type="radio" value="PokePartay" name="party" />PokePartay</label> <label><input type="radio" value="Equilibrium" name="party" />Equilibrium Party</label> </div> <br /> <input type="Submit" value="Submit" /> <input type="hidden" value="<?php $tz = new DateTimeZone('America/Indianapolis'); $date = new DateTime('now', $tz); echo $date->format('m-d-Y h:i:s') . "\n"; ?>" name="time" /> <?php if (isset($_POST['submit'])) { $involvements = $_POST['involvement']; foreach($involvements as $involvement) { $query2 = "INSERT INTO votes (involvement) VALUES ('$involvement')"; $result2 = mysql_query($ballot, $query2) or die(mysql_error()); } } ?> <input type="hidden" name="MM_insert" value="Ballot" /> </form> </div> <br /> <br /> <br /> <br /> </div> </td> </tr> </table> </body> </html> <?php mysql_free_result($Recordset1); ?> Thanks, Philip Ulrich Hi, basically, here's the deal: I have a lit of checkboxes that are added by the admin (there's an unlimited amount, just depends on how many are added). Then, those are put in a form, in which the user picks whichever ones need to be chosen and those values get sent to a MySQL table. Here's the code that displays the checkboxes Code: [Select] <?php $sql="SELECT * FROM category ORDER BY categoryID ASC"; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ echo "<input type='checkbox' id='". $row['categoryName'] ."' name='licensed[]' value='" . $row['categoryID'] ."' /><label for='". $row['categoryName'] ."'><br>" . $row['categoryName'] ."</label><br>"; } ?> What I'm making now, is an edit form where whichever checkboxes were checked, will show up checked in the edit form. But I'm not really sure how to go about this, since there is only one actual input tag in the code, I can't select the different ones. I also have this SQL query which selects whichever boxes were inputted into the DB Code: [Select] $sql2="SELECT * FROM category, categoryInfo WHERE category.categoryID = categoryInfo.categoryID AND categoryInfo.parentID = $parentID"; $result2=mysql_query($sql2); Where $parentID is the ID of whichever form you're editing. But yes, I'm basically not really sure how to go about this and would like some help figuring this out Thanks for your time Hi, I have this form which will create a checkbox list using data from my database and also determin if a checkbox had been checked before and check if it had. <form style="text-align:center" name="PrefRestaurant" id="PrefRestaurant" action="preferances_check.php" method="post"><table align="center"> <?php checkbox(id, name, restaurants, id); ?></table> <input type="submit" name="Prefer" id="Prefer" value="Επιλογή"/></form> function checkbox($intIdField, $strNameField, $strTableName, $strOrderField, $strMethod="asc") { $strQuery = "select $intIdField, $strNameField from $strTableName order by $strOrderField $strMethod"; $rsrcResult = mysql_query($strQuery); while ($arrayRow = mysql_fetch_assoc($rsrcResult)) { $testqry = "SELECT * FROM user_restaurant WHERE user_id = $_SESSION[UserId] AND restaurant_id = $arrayRow[id]"; $rsltestqry = mysql_query($testqry); $numrows = mysql_num_rows($rsltestqry); if ($numrows == 1) { echo "<tr align=\"left\"><td><input type=\"checkbox\" name=\"restaurant[]\" value=\"$arrayRow[id]\" checked/>$arrayRow[name]</td></tr>"; } else{ echo "<tr align=\"left\"><td><input type=\"checkbox\" name=\"restaurant[]\" value=\"$arrayRow[id]\" />$arrayRow[name]</td></tr>"; } } } Now the part which I can't get to work is when I'm trying to store the new values in my database. When I click the submit button I clear my database of any row that is related to the currently loggedin user and I want to store his new preferences (checked cheboxes). I've read that only the cheked checkboxes' values are POSTed so I did this (preferances_check.php) foreach($_POST['restaurant'] as $value) { $query="INSERT INTO user_restaurant VALUES ('$_SESSION[UserId]','$value')"; } But it is not working, nothing gets written in my table Could someone please enlighten me on this? Thnks! I want to delete rows in a table of my database using check-box. Here are my codes below: Code: [Select] <?php $con = mysql_connect('localhost', 'root', '') or die ('Connection Failed'); mysql_select_db('img', $con) or die ('Connection Failed'); $display = mysql_query("SELECT * FROM photos WHERE email='$lemail'"); echo '<input type="submit" value="Delete" name="del"/>'; echo "<table> <tr> <th>#</th> <th>Images</th> <th>Image description</th> <th>Delete</th> </tr>"; while($row = mysql_fetch_array($display)) { echo "<tr>"; echo "<td>".$row['img_ID']."</td>"; echo "<td><img src='folder/".$row['imaged']."' alt='alt text' width='100' height='100' class='thumb'/> </td>"; echo "<td>".$row['image_description']."</td>"; echo '<td><input type="checkbox" name="delete[]" value="'.$row['img_ID'].'"/></td>'; echo "</tr>"; } echo "</table>"; echo "</form>"; if (isset($_POST['delete'])) { $del = $row['img_ID']; for($i=0;$i<count($_POST["delete"]);$i++) { if($_POST["delete"][$i] != "") { $str = "DELETE FROM photos WHERE img_ID='$del' "; mysql_query($str); echo "Record Deleted."; } } } mysql_close($connect); ?> Here are the problems: 1/ Not working at all, I mean no image is being deleted 2/ At then end, I display a message that the record has been deleted, but if I check multiple checkbox, it keeps writing the message "Records deleted" multiple times My images are stored in a folder while its details in database... Help, thank you So I've spent 2 days now searching the web on how to make my checkbox array on my form insert the value selected by the user into my database. Here is the code that I've written. All fields except for the checkbox array works fine. <?php virtual('/budgets/Connections/connAdmin.php'); ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if (isset($_POST['submit'])) { $workStyle = $_POST['art_photos']; // Setting up a blank variable to be used in the coming loop. $allStyles = ""; // For every checkbox value sent to the form. foreach ($workStyle as $style) { // Append a string called $allStyles with the current array element, and then add a comma and a space at the end. $allStyles .= $style . ", "; } // Delete the last two characters from the string. $allStyles = substr($allStyles, 0, -2); echo "<p>The resulting string is: <strong>$allStyles</strong></p>\r\n"; } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO daily_budget (rundate, slug, reporter, budgetInfo, notes, `section`, deadline, art_photos sidebar, sBudget) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['rundate'], "text"), GetSQLValueString($_POST['slug'], "text"), GetSQLValueString($_POST['reporter'], "text"), GetSQLValueString($_POST['budgetInfo'], "text"), GetSQLValueString($_POST['notes'], "text"), GetSQLValueString($_POST['section'], "text"), GetSQLValueString($_POST['deadline'], "text"), GetSQLValueString($_POST['art_photos'], "text"), GetSQLValueString($_POST['sidebar'], "text"), GetSQLValueString($_POST['sBudget'], "text")); mysql_select_db($database_connAdmin, $connAdmin); $Result1 = mysql_query($insertSQL, $connAdmin) or die(mysql_error()); } ?> <!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>Budget Record</title> </head> <body> <?php if (isset($error)) { echo '<ul>'; foreach($error as $alert) { echo "<li class='warning'>$alert</li>\n"; } echo '</ul>'; } ?> <form action="<?php echo $editFormAction; ?>" method="POST" name="form1" id="form1"> <table align="center" width="60%" border="2" bgcolor="#FFFFFF"> <tr valign="baseline"> <td width="14%" align="right" nowrap="nowrap"><STRONG>Rundate:</STRONG></td> <td width="86%"> <input type="text" name="rundate" size="30" value="" id="jQueryUICalendar2"/> <script type="text/javascript"> // BeginWebWidget jQuery_UI_Calendar: jQueryUICalendar2 jQuery("#jQueryUICalendar2").datepicker(); // EndWebWidget jQuery_UI_Calendar: jQueryUICalendar2 </script></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><STRONG>Section:</STRONG></td> <td> <select name="section"> <option value=""></option> <option value="A1">A1</option> <option value="Pickup All">Pickup All</option> <option value="Region">Region</option> <option value="Atlantic">Atlantic</option> <option value="Business">Business</option> <option value="Features">Features</option> <option value="Sports">Sports</option> </select> </td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Slug:</strong></td> <td><span id="sprytextfield2"> <input type="text" name="slug" value="" size="32" /> <span class="textfieldRequiredMsg">REQUIRED</span></span><span style="color: #F00; font-weight: bold; font-size: 10px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Budget Information:</strong></td> <td><span id="sprytextarea1"> <textarea name="budgetInfo" cols="50" rows="4"></textarea> <span class="textareaRequiredMsg">Required.</span></span><span style="color: #F00; font-weight: bold; font-size: 11px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Notes:</strong></td> <td><input type="text" name="notes" value="" size="32" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Reporter:</strong></td> <td><span id="sprytextfield3"> <input type="text" name="reporter" value="" size="32" /> <span class="textfieldRequiredMsg">Required.</span></span><span style="color: #F00; font-weight: bold; font-size: 10px;"></span></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Deadline:</strong></td> <td><input type="text" name="deadline" size="30" value="Enter date" id="jQueryUICalendar1"/><script type="text/javascript"> // BeginWebWidget jQuery_UI_Calendar: jQueryUICalendar2 jQuery("#jQueryUICalendar1").datepicker(); // EndWebWidget jQuery_UI_Calendar: jQueryUICalendar2 </script> </td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Artwork:</strong></td> <td><label> <input type="checkbox" name="art_photos[]" value="factbox" id="art_photos_0" /> Factbox</label> <label> <input type="checkbox" name="art_photos[]" value="graphic" id="art_photos_1" /> Graphic</label> <label> <input type="checkbox" name="art_photos[]" value="photo" id="art_photos_2" /> Photo</label> <label> <input type="checkbox" name="art_photos[]" value="video" id="art_photos_3" /> Video</label> <br /></td> </tr> <tr> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> <strong>Sidebar:</strong></td> <td valign="baseline"><span id="spryradio2"> <label> <input type="radio" name="sidebar" value="y" id="sidebar_0" /> Yes</label> <br /> <label> <input type="radio" name="sidebar" value="n" id="sidebar_1" /> No</label> <br /> <span class="radioRequiredMsg"><strong style="font-size: 11px">REQUIRED.</strong></span></span> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"><strong>Sidebar Information:</strong></td> <td><input type="text" name="sBudget" value="" size="32" /></td> </tr> <tr valign="baseline"> <td nowrap="nowrap" align="right"> </td> <td><input type="submit" value="Insert record" /></td> </tr> </table> <input type="hidden" name="MM_insert" value="form1" /> </form> <p> </p> <h3><a href="/new_budget/admin/manage_budgets.php"><strong>View your budget entry, make changes or delete your budget.</strong></a></h3> <script type="text/javascript"> <!-- jQuery("#jQueryUICalendar1").datepicker(); jQuery("#jQueryUICalendar2").datepicker(); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none", {maxChars:15, validateOn:["change"]}); var sprytextarea1 = new Spry.Widget.ValidationTextarea("sprytextarea1", {validateOn:["change"]}); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3"); var spryradio2 = new Spry.Widget.ValidationRadio("spryradio2"); //--> </script> </body> </html> have a database with a column of datatype EM (multiple selection, say apples, oranges, grapes) I want to have a form with checkboxes for those values (apples, oranges, grapes etc) so one can select a breakfast basket type that contains for example, oranges and grapes. It would pull from the database those baskets with those selection of fruits (specified in the column 'Fruits', which is a EM datatype column. (I have a multiple selection when entering the values for the column.) Can it be done? Should I make another table with FruitNames? Ok, so I've spent quite a bit of time piecing together this solution from a variety of sources. As such, I may have something in my code below that doesn't make sense or isn't neccessary. Please let me know if that is the case. I'm creating an administrative form that users will you to add/remove items from a MySQL table that lists open positions for a facility. The foreach loop generates all of the possible job specialties from a table called 'specialty_list'. This table is joined to a second table ('open_positions') that lists any positions that have been selected previously. Where I'm stuck is getting the checkbox to be checked if the facility_ID from the open_positions table matches the $id passed in the URL via ?facility_id=''. Here's where I am so far: $query = "SELECT specialty_list.specialty_displayname , specialty_shortname , open_positions.position , facility_ID FROM specialty_list LEFT OUTER JOIN open_positions ON open_positions.position = specialty_list.specialty_shortname ORDER BY specialty_list.specialty_shortname"; $results = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($results)) { $positions[$row['specialty_shortname']] = $row['specialty_displayname']; } echo "<form method='POST' action='checkbox.php'>"; foreach($positions as $specialty_shortname => $specialty_displayname) { $facility_ID = $row['facility_ID']; $checked = $facility_ID == $row['facility_ID'] ? ' checked' : ''; echo "<input type='checkbox' name='position[]' value=\"{$specialty_shortname}\"{$checked}> {$specialty_displayname}</input><br/>"; } echo "<input type='hidden' name='facility_ID' value='$id'>"; echo "<input type='submit' value='Submit Checkboxes!'>"; echo "</form>"; Any ideas how to get this working? I feel like I'm very close, but I just can't get it. I also tried starting from scratch with a WHILE statement instead of a FOREACH, but haven't tweaked it enough to prevent duplicate checkboxes. With that in mind, here it is, just in case that's a better direction: $query = "SELECT specialty_list.specialty_displayname , specialty_shortname , open_positions.position , facility_ID FROM specialty_list LEFT OUTER JOIN open_positions ON open_positions.position = specialty_list.specialty_shortname ORDER BY specialty_list.specialty_shortname"; $results = mysql_query($query) or die(mysql_error()); echo "<form method='POST' action='checkbox.php'>"; while($row=mysql_fetch_assoc($results)) { $facility_ID = $row['facility_ID']; $specialty_shortname = $row['specialty_shortname']; $specialty_displayname = $row['specialty_displayname']; if ($facililty_ID==$id) { $checked=' checked'; } echo "<input type='checkbox' name='position[]' value=\"$specialty_shortname\"$checked> $specialty_displayname</input><br/>"; } echo "<input type='hidden' name='facility_ID' value='$id'>"; echo "<input type='submit' value='Submit Checkboxes!'>"; echo "</form>"; Hey guys, I can't wrap my head around how to make this work right... I have three tables: Code: [Select] CREATE TABLE `games` ( `g_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(150) DEFAULT NULL, PRIMARY KEY (`g_id`)); CREATE TABLE IF NOT EXISTS `game_player` ( `r_id` int(11) NOT NULL AUTO_INCREMENT, `p_id` int(11) DEFAULT NULL, `g_id` int(11) DEFAULT NULL, `bool` int(1) NOT NULL DEFAULT '0', PRIMARY KEY (`r_id`)); CREATE TABLE IF NOT EXISTS `players` ( `p_id` int(11) NOT NULL AUTO_INCREMENT, `playerid` varchar(150) NOT NULL, PRIMARY KEY (`p_id`), UNIQUE KEY `playerid` (`playerid`)); The players table is my list of users, and they're tied to the list of games via the game_player table. So here's my issue... I'm trying to show the full list of games, and then check mark each record where the player does play it. This is what I have so far - it shows all the games, but it's not checking the boxes. Code: [Select] $result = mysql_query("SELECT * FROM games") or die(mysql_error()); while($row = mysql_fetch_array($result)) { $newquery = "SELECT * FROM game_player, players WHERE game_player.p_id = players.p_id AND game_player.g_id = ".$row['g_id']. " AND players.playerid = {$userid}"; $query = mysql_query($newquery) or die(mysql_error()); if($query['bool'] == 1) { $set_checked = " CHECKED"; } else{ $set_checked = ""; } echo "<input type=\"checkbox\" name=\"box1\" value=\"".$query['g_id']."\"" . $set_checked . "/>".$row['name']."<br />\n"; } Hey guys, I am trying to input data into a mysql database from data thats been added by a jquery form with cloned fields. It is working however it adds the first row correctly then a blank row and then the rest of the rows correctly The code is this $x=0; do { $fga=$_POST['ID'.$x.'fga']; $fgm=$_POST['ID'.$x.'fgm']; $fta=$_POST['ID'.$x.'fta']; $ftm=$_POST['ID'.$x.'ftm']; $tpa=$_POST['ID'.$x.'tpa']; $tpm=$_POST['ID'.$x.'tpm']; $fta=$_POST['ID'.$x.'fta']; $ftm=$_POST['ID'.$x.'ftm']; $stl=$_POST['ID'.$x.'stl']; $trb=$_POST['ID'.$x.'trb']; $ast=$_POST['ID'.$x.'ast']; $blka=$_POST['ID'.$x.'blka']; $blkf=$_POST['ID'.$x.'blkf']; $tovr=$_POST['ID'.$x.'tovr']; mysql_query("INSERT INTO stats (gameId, fga, fgm, tpa, tpm, fta, ftm, ast, stl, trb, blka, blkf, tovr) VALUES ('$gameId', '$fga', '$fgm', '$tpa', '$tpm', '$fta', '$ftm', '$ast', '$stl', '$trb', '$blka', '$blkf', '$tovr')")or die("<div class='errmsg'>Insert Error: ".mysql_error()."</div><br /> \n"); $x++; Can anyone see what ive done wrong? Thanks 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 |