PHP - Group Of Checkboxes Generated By A Database And Compared Against The Database.
I have a very tricky php problem here. At least for me.
On a page that is editing a job entry. I have a database generated group of checkboxes some of which have been checked when the job was entered. So the script has to do two things generate the complete list of checkboxes and check the ones that have already been selected in the job request. The below script is what I've done trying to figure it out. Description of what I'm trying to do: I'm generating the the boxes with a call to my database for the list of checkboxes. Then I'm building an array with all the possible items that could be checked to compare against. Ok here is where I think my first problem is. I need to make a second query to another table "worklog" in the same database. This is where the list of checked items are stored. What is the best way to do this? A second query seems wrong "or at least not efficient" Code: [Select] <div class="text">Job Type (<a class="editlist" href="javascript:editlist('listedit.php?edit=typelist',700,400);">edit list</a>):</div> <div class="field"> <?PHP $connection=mysql_connect ("localhost", "user", "password") or die ("I cannot connect to the database."); $db=mysql_select_db ("database", $connection) or die (mysql_error()); $query = "SELECT type FROM typelist ORDER BY type ASC"; $sql_result = mysql_query($query, $connection) or die (mysql_error()); $i=1; echo '<table valign="top"><tr><td>'; while ($row = mysql_fetch_array($sql_result)) { $type = $row["type"]; if ($i > 1 && $i % 26 == 0) echo '</td><td>'; else if ($i) echo ''; ++$i; $aTypes = array ("Spec Ad Campaign", "100 x 100 Logo", "100 x 35 (Featured Developer/Broker)", "100 x 40 (Featured Lender)", "120 x 180 (Home Page Auto)", "120 x 45 (Half Tile - Jobs)", "120x60 (Section Sponsor)", "125 x 40 (Profile Page logo)", "135 x 31 (Autos)", "135 x 60 (Autos)", "135 x 60 (Logotile - Jobs)", "150 x 40 (Auto Logo)", "160 x 240 (monster tile)", "160 x 400 (Skyscraper)", "160 x 600 (Tower)", "170x30 (Section Sponsor)", "240 x 180 JPG/GIF Auto Video", "240 x 180 size FLV video ", "300 x 250 (Story Ad)", "300 x 600 (Halfpage)", "468 x 60 (Banner Jpg/Gif)", "728 x 90 (Leaderboard)", "95 x 75 (Sweeps Logo) ", "Agent Profile Page", "Contest", "Creative Change", "Employer Profile", "Holiday Shop", "Home of the Week", "HP Half Banner (234 x 60 Static)", "Mobile Ads (320x53 *300x50*216x36*168x28)", "Newsletter", "Peelback", "Pencil Ad", "Print", "Real Deals", "Resize ad campaign", "Roll-Over Skyscraper", "Site Sponsor logo (170x30)", "Splash Page Production", "Travel Deals Update", "Video Ad", "Web Development", "Web Maintenance", "Web Quote (or Design)"); $dbTypes = explode(',',$row['type']); foreach ($aTypes as $type){ if(in_array($aType,$dbTypes)){ echo "<input style='font-size:10px;' name='type[]' type='checkbox' value='$type' CHECKED><span style='color:#000;'>$type</span></input><br/>"; }else { echo "<input style='font-size:10px;' name='type[]' type='checkbox' value='$type'><span style='color:#000;'>$type</span></input><br/>"; } } } echo '</td></tr></table>'; ?> </div> Similar TutorialsG'day to all, I need some help building a site that has the ability to accept members and deposit those members in a database. When the members join they will have the ability to add features to their profile; like, skills and certificates. Upload pictures of certificates and a profile pic. The admin area needs to have the ability to add membership types and give those members specific abilities. The admin also needs to have the ability to create profile options, like additional skills. Like a type 1 member has the ability search and see all type 2 members who have a particular skill set. type 2 members just get to see their own profile and the tasks the type 1 members list.
This all might sound like a bunch of brambles but please let me know if you are interested and we can get more involved. Thank you so very much for your help in advanced... Juan Hi all, Does anyone know if it's possible to generate a dropdown list filled with database information. I use the following to get the information from the database: $query = "SELECT Name FROM city WHERE member_ID = '$member_ID'"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { echo $row['Name'] . '<br>'; } Thnx Ryflex Hey everyone i having some trouble updating records in my databse using checkbox from a form. I can update the records, but i can't figure out how to remove records at the same time. I've posted the code that i'm using to update below foreach($_POST['tag'] as $k=>$l){ $tag = mysql_real_escape_string($_POST['tag'][$k]); $check_tags = mysql_query("SELECT * FROM file_cats WHERE category='$tag'") or die(mysql_error()); $num_tags = mysql_num_rows($check_tags); if($num_tags==0){ $add_tag = mysql_query("INSERT into file_cats (fileID, category) VALUES('$fileID', '$tag')") or die(mysql_error()); } } This code inserts new records based on what the user checked. If it exist it won't add a new row, if it doesn't exist then it will add a new row. but like i said how can remove a row if the box is no longer checked? I've tried using foreach(empty($_POST['tag'] as $k => $l){ $tag = empty($_POST['tag']['$k']; } But that didn't work basically nothing was deleted. Has anyone done something like this before? if so i would appreciate any help you could give Hi people. I have a form which inputs into a database. Here is the code that inserts a yes no option... Code: [Select] <select name = "consent"> <option value = "Yes" <?php if ($_POST['consent'] == 'Yes') { echo 'selected="selected"'; } ?>>Yes</option> <option value = "No" <?php if ($_POST['consent'] == 'No') { echo 'selected="selected"'; } ?>>No</option> </select> However, I have been asked if I can make it a yes or no checkbox instead. Please can you tell me how I need to code it so that the "yes" or "no" is recorded in the DB. At the moment I just have this Code: [Select] <input name="consent" type="checkbox" value="Yes" />Yes<br /> <input name="consent" type="checkbox" value="No" />No<br /> Thanks in advance VinceG I use the following code to generate a scrollable checkbox list of options: Code: [Select] <html> <form action="SCRIPT.php"> <?php $expList = array('Engineering ','Science', 'Art', 'IT', 'Electronics', 'Communications'); sort($expList); $tmp = array(); $i = 1; $tmp[] = '<ul style="height: 95px; overflow: auto; width: 200px; border: 1px solid #480091; list-style-type: none; margin: 0; padding: 0;">'; foreach ($expList as $option) { $tmp[] = '<li id="li' . $i . 'b"><label for="chk' . $i . 'b"><input name="chk' . $i . 'b" id="chk' . $i . 'b" type="checkbox" onchange="Enable(\'chk' . $i . 'b\',\'li' . $i . 'b\')">' . $option . '</label></li>'; $i++; } $tmp[] = '</ul>'; echo implode("\n",$tmp) . "\n"; ?> <input type="submit"> </form> </html> But there are in fact over 50 options (not just 6) and they are in fact stored in an array $expList in an external php file called LISTS.php. As you can see, the checkbox list consists of checkboxes chk1b, chk2b, chk3b, etc. with associated labels (Art, Communications, Electronics, etc.). What I need in SCIPT.php is code that will insert each of the labels where the associated checkbox has been checked in my MySQL database. E.g. in this particular case: if chk1b & chk3b have been checked, 'Art' & 'Electronics' will be inserted. Also, I want the label of the first checked checkbox to be inserted in the (database) table column 'Exp1', the 2nd one in 'Exp2'.........25th one in 'Exp25' (I already have a script that allows a maximum of 25 checkboxes to be checked). I'm guessing some sort of 'foreach' loop is required, but I can't quite work it out. Pls help! Many thanks! after cloasing connection of database i still got the values form database. Code: [Select] <?php session_start(); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ require_once '../database/db_connecting.php'; $dbname="sahansevena";//set database name $con= setConnections();//make connections use implemented methode in db_connectiong.php mysql_select_db($dbname, $con); //update the time and date of the admin table $update_time="update admin set last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname'limit 3,4"; //my admin table contain 5 colums they are id, username,password, last_logged_date, last_log_time $link= mysql_query($update_time); // mysql_select_db($dbname, $link); //$con=mysql_connect('localhost', 'root','ijts'); $result="select * from admin where username='a'"; $result=mysql_query($result); mysql_close($con); //here i just check after closing data baseconnection whether i do get reselts but i do, why? echo "after the cnnection was closed"; if(!$result){ echo "cont fetch data"; }else{ $row= mysql_fetch_array($result); echo "id".$row[0]."usrname".$row[1]."passwped".$row[2]."date".$row[3]."time".$row[4]; } // echo "<html>"; //echo "<table border='1' cellspacing='1' cellpadding='2' align='center'>"; // echo "<thead>"; // echo"<tr>"; // echo "<th>"; // echo ID; // echo"</th>"; // echo" <th>";echo Username; echo"</th>"; // echo"<th>";echo Password; echo"</th>"; // echo"<th>";echo Last_logged_date; echo "</th>"; // echo "<th>";echo Last_logged_time; echo "</th>"; // echo" </tr>"; // echo" </thead>"; // echo" <tbody>"; //while($row= mysql_fetch_array($result,MYSQL_BOTH)){ // echo "<tr>"; // echo "<td>"; // echo $row[0]; // echo "</td>"; // echo "<td>"; // echo $row[1]; // echo "</td>"; // echo "<td>"; // echo $row[2]; // echo "</td>"; // echo "<td>"; // echo $row[3]; // echo "</td>"; // echo "<td>"; // echo $row[4]; // echo "</td>"; // echo "</tr>"; // } // echo" </tbody>"; // echo "</table>"; // echo "</html>"; session_destroy(); session_commit(); echo "session and database are closed but i still get values from doatabase session is destroyed".$_SESSION['admin']; ?> session is destroyed but database connection is not closed. thanks hello everyone, I am about to start coding my pages to display results from a database but before i do i want to know information about the following : Is it best to upload images to a database?and display them accordingly? or is it best to use images from a directory? What is most commonly used and or more reliable? Another topic i have trouble finding information on is actually positioning the output from you mysql database, is this practice done with tables?fields and rows? What is this method called? And is there more then one way to go about controlling result layout on your page? Sorry about the 1001 questions , but i am unable to find a clear answer on the topic ..especially question two . Thanks in advance. At the moment I am creating a search function for my website. The approach I have in mind is a pseudo-PHP database. To give an example: A HTML form will submit the results to a PHP file. HTML FORM - Colour: Black PHP RESULT PAGE - if ($_POST['color'] == 'Black') {readfile("./products/black/*.html");} HTML FORM - Price: <$50 PHP RESULT PAGE - if ($_POST['Price'] == '<$50') {readfile("./products/less50/*.html");} The problem here is if there is an item that is black and costs less than $50, then its going to be listed twice. There is probably some code I can write to ommit the listing of duplicate entries, but it is probably going to be messy, so I am wondering if its better to use a centralized MySQL database, rather than a pseudo-PHP database? I've never used MySQL and don't know much about it and this is my first real attempt at using PHP. I have a standard form that displays users current data from a mysql database once logged in(code obtained from the internet). Users can then edit their data then submit it to page called editform.php that does the update. All works well except that the page does not display the updated info. Users have to first logout and login again to see the updated info. even refreshing the page does not show the new info. Please tell me where the problem is as i am new to php.
my form page test.php
<?PHP require_once("./include/membersite_config.php"); if(!$fgmembersite->CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } ?> <form action="editform.php?id_user=<?= $fgmembersite->UserId() ?>" method="POST"> <input type="hidden" name="id_user" value="<?= $fgmembersite->UserId() ?>"><br> Name:<br> <input type="text" name="name" size="40" value="<?= $fgmembersite->UserFullName() ?>"><br><br> Email:<br> <input type="text" name="email" size="40" value="<?= $fgmembersite->UserEmail() ?> "><br><br> Address:<br> <input type="text" name="address" size="40" value="<?= $fgmembersite->UserAddress() ?> "><br><br> <button>Submit</button>my editform.php <?php $con = mysqli_connect("localhost","root","user","pass"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"UPDATE fgusers3 SET name = '".$_POST['name']."', email= '".$_POST['email']."', address= '".$_POST['address']."' WHERE id_user='".$_POST['id_user']."'"); header("Location: test.php"); ?> Hi guys, I was just wondering if anyone could help me. I've got a My_SQL database containing articles, a summary for the article and a date. I have a basic CMS system set-up, but I want to create a script that when users sign up to a mail list it forwards the summary and dates of the articles database. If that makes sense? But I only want it to forward the most recent 5 rows. I'm pretty new to PHP and I've been mostly following tutorials thus far, but this is quite specific. Thanks in advance! hello I want query from one table and insert in another table on another domain . each database on one domain name. for example http://www.site.com $con1 and http://www.site1.com $con. can anyone help me? my code is : <?php $dbuser1 = "insert in this database"; $dbpass1 = "insert in this database"; $dbhost1 = "localhost"; $dbname1 = "insert in this database"; // Connecting, selecting database $con1 = mysql_connect($dbhost1, $dbuser1, $dbpass1) or die('Could not connect: ' . mysql_error()); mysql_select_db($dbname1) or die('Could not select database'); $dbuser = "query from this database"; $dbpass = "query from this database"; $dbhost = "localhost"; $dbname = "query from this database"; // Connecting, selecting database $con = mysql_connect($dbhost, $dbuser, $dbpass) or die('Could not connect: ' . mysql_error()); mysql_select_db($dbname) or die('Could not select database'); //query from database $query = mysql_query("SELECT * FROM `second_content` WHERE CHANGED =0 limit 0,1"); while($row=mysql_fetch_array($query)){ $result=$row[0]; $text=$row[1]."</br>Size:(".$row[4].")"; $alias=$row[2]; $link = '<a target="_blank" href='.$row[3].'>Download</a>'; echo $result; } //insert into database mysql_query("SET NAMES 'utf8'", $con1); $query3= " INSERT INTO `jos_content` (`id`, `title`, `alias`, `) VALUES (NULL, '".$result."', '".$alias."', '')"; if (!mysql_query($query3,$con1)) { die('Error: text add' . mysql_error()); } mysql_close($con); mysql_close($con1); ?> the second database found on the cloud
i try to get JSON data but how to insert and update them to another online database with the same table my php script to return json data <?php include_once('db.php'); $users = array(); $users_data = $db -> prepare('SELECT id, username FROM users'); $users_data -> execute(); while($fetched = $users_data->fetch()) { $users[$fetchedt['id']] = array ( 'id' => $fetched['id'], 'username' => $fetched['name'] ); } echo json_encode($leaders);
i get
{"1":{"id":1,"username":"jeremia"},"2":{"id":2,"username":"Ernest"}} Edited March 24 by mahenda <?php $image_url = 'images/'; //User defined variables for page settings $rows_per_page = 2; $cols_per_page = 4; //Master array of ALL the images in the order to be displayed $images = array( 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg', 'image10.jpg', 'image11.jpg', 'image12.jpg', 'image13.jpg', 'image14.jpg', 'image15.jpg', 'image16.jpg', 'image17.jpg', 'image18.jpg', 'image19.jpg' ); //END USER DEFINED VARIABLES //System defined variable $records_per_page = $rows_per_page * $cols_per_page; $total_records = count($images); $total_pages = ceil($total_records / $records_per_page); //Get/define current page $current_page = (int) $_GET['page']; if($current_page<1 || $current_page>$total_pages) { $current_page = 1; } //Get records for the current page $page_images = array_splice($images, ($current_page-1)*$records_per_page, $records_per_page); //Create ouput for the records of the current page $ouput = "<table border=\"1\">\n"; for($row=0; $row<$rows_per_page; $row++) { $ouput .= "<tr>\n"; for($col=0; $col<$cols_per_page; $col++) { $imgIdx = ($row * $rows_per_page) + $col; $img = (isset($page_images[$imgIdx])) ? "<img src=\"{$image_url}{$page_images[$imgIdx]}\" />" : ' '; $ouput .= "<td>$img</td>\n"; } $ouput .= "</tr>\n"; } $ouput .= "</table>"; //Create pagination links $first = "First"; $prev = "Prev"; $next = "Next"; $last = "Last"; if($current_page>1) { $prevPage = $current_page - 1; $first = "<a href=\"test.php?page=1\">First</a>"; $prev = "<a href=\"test.php?page={$prevPage}\">Prev</a>"; } if($current_page<$total_pages) { $nextPage = $current_page + 1; $next = "<a href=\"test.php?page={$nextPage}\">Next</a>"; $last = "<a href=\"test.php?page={$total_pages}\">Last</a>"; } ?> <html> <body> <h2>Here are the records for page <?php echo $current_page; ?></h2> <ul> <?php echo $ouput; ?> </ul> Page <?php echo $current_page; ?> of <?php echo $total_pages; ?> <br /> <?php echo "{$first} | {$prev} | {$next} | {$last}"; ?> </body> </html> This current code provides an easy way of uploading pictures and having the other pictures move automatically without the need of a database. But I must wonder, if doing this on a database would be faster. Would it be? I mean the example adobe shows I'm only using 19 pictures, but if I ever reach say 1000 pictures, would the php file be too big? Should I just make a database now or it doesn't matter? Also, the code above, which I took from a phpfreak member, has the pagination not working. Anyone care to do a diagnosis? Thanks! Hi, my PHP code currently outputs the results from a users search by querying a backend postgresql database. As result/row is retuned to the user i would like to be able to detect whether or not they have checked a checkbox at the end of each rown in which case multiple rows can then be deleted from the database upon the user clicking a 'delete multiple records' button. I have no problem in being able to display the checkboxes on the webpage but i am a little unsure as to how to refernce them and detect which ones the user has checked. Given my database stores hostnames/IP addresses would it be best to name each checkbox to reflect the hostname or name the value it returns when checked to reflect the hostname. Given the above and that I also store the results of a users search in a $_SESSION['hosts'][][] array how can I then tie the two together? Thanks for reading. i have got this code and i can get everything to work on this except the part to get the drop down menu for the sections, i can get the 4 sections to show but every time i try to add something to any section it is added to the last section no matter what please help Code: [Select] <?php require("connection/connection.php"); include("connection/functions.php"); ?> <HTML> <head> <link href="css/style.css" rel="stylesheet" media="screen" type="text/css" /> <script src="javascript/functions.js" type="text/javascript"></script> <title>.: Bookmarks :.</title> </head> <body class="musiclist"> <div id="content" style="top: 36px"> <form method="post" action="AddBookmark.php"> <span class="graytitle">Add Bookmark</span> <ul class="pageitem"> <li class="bigfield"><input type="text" name="BookmarkName" placeholder="Bookmark Name" /></li> <li class="bigfield"><input type="text" name="KindofBookmark" placeholder="Kind of Bookmark" /></li> <li class="bigfield"><input type="text" name="BookmarkLink" placeholder="Bookmark Link" /></li> <li class="select"><select name="d"> <?php $getbookmarksections = mysql_query("SELECT * FROM bookmarksections"); confirm_query($getbookmarksections); while($getbm = mysql_fetch_array($getbookmarksections)){ $bmid = $getbm["ID"]; $sn = $getbm["SectionName"]; echo "<option value=\"$bmid\">$sn</option>"; } ?> </select><span class="arrow"></span></li> <li class="button"> <input name="AddBookmark" type="submit" value="Add Bookmark" /> </li> </ul> </form> <?php if(isset($_POST["AddBookmark"])){ $Bookmark = $_POST["BookmarkName"]; $KindofBookmark = $_POST["KindofBookmark"]; $BookmarkLink = $_POST["BookmarkLink"]; $add = mysql_query("INSERT INTO `bookmarks` (`ID`,`SectionID`,`KindofBookmark`,`Bookmark`,`BookmarkLink`) VALUES ('NULL','$bmid','$KindofBookmark','$Bookmark','$BookmarkLink')"); confirm_query($add); if($add == TRUE){ echo "<span class=\"graytitle\">Bookmark '$Bookmark' in '$sn' Added.</span>"; } } ?> </div> <div id="footer"> </div> </body> </HTML> <?php //Close Connection if(isset($connection)){ mysql_close($connection); } ?> Hi, Just need to know if I am on the right lines, basically I am about to create two tables; one to hold customer information and another to hold information the customer gave me. Both tables will be populated with information that they give me at the same time (in other words from a single form). Just want to know, if I have a field called ID set to a primary key in both the tables, will that be enough to link them both together? Furthermore, what would the mySQL code look like if I wanted to view all the information referencing to specific ID? so info from the customer table and the other. Any and all help would be great. Lee Hi there, *little heads up: English isn't my native language, so excuse me for any mistakes in spelling etc.* I've got a register/login script with activation mail, I secure my pages with this bit of code: Code: [Select] } if (!$HTTP_SESSION_VARS["ingelogd"]) { header("Location: login.php"); } Because if someone logs in, the session is made: Code: [Select] // bekijk of de gegevens juist zijn if (mysql_num_rows($res) >= 1) { // registreer sessie (of cookie) $ingelogd = mysql_result($res, 0); session_register(ingelogd); // setcookie("ingelogd", "$ingelogd", time() + 1 * 86400); echo "<p style=\"font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #000000;\"> U bent succesvol ingelogd.</p>"; echo "<p style=\"font-family: Arial, Helvetica, sans-serif; font-size: 13px; color: #000000;\"> Klik hier om <a href=\"home.php\">verder</a> te gaan.</p>"; } My question: When someone registered, they entered their 'real' name, which is then placed into the database in the same row as the username, password etc. I would like to state on the homepage which is secured 'Welcome 'Name'!' I do I get this 'Name' value out of the database and into my page? Thanks in advance! Sander When I do this: $matches++; $sql_update_matches = mysql_query("UPDATE Live_Event SET matches='$matches' WHERE id='$show_id' AND promo_id='$promotion_id'"); But when it should update the database from 0 to 1, it update it to U. What is the problem? Not sure if I can post this here, or if I should go to a mySQL forum but... I'm trying to keep track of my user's "score". Each time they do a certain thing they get a preset amount of points, depending on what they did. The way I see it would be having a table that is joined to the user's ID, and have a column for each task. Then when they do a task the number in that column will go up. Then I will multiply that number by amount the task is worth. I can't just adjust there score because they need to be able to see what they did. So I hope that made sense. And if you know a better way to deal with this please let me know! |