Jump to content

Search the Community

Showing results for tags 'mysql'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I have searched over 1500 posts over the last 2 weeks and have not found the solution to make my code work. My registration and login forms work correctly but when the user logins to add or edit information the sql database does not update with the users input and the error/updated message does not echo. My users register with name, surname, email and password but once they login they need to add to their personal information and later be able to edit the personal information. But nothing I've tried has worked... my code is as follows: <?php include_once "connect_to_mysql.php"; $id = $_SESSION['id']; if ($_POST['username']) { $title = $row["title"]; $username = $row["username"]; $surname = $row["surname"]; $identityno = $row["identityno"]; $gender = $row["gender"]; $birthdate = strftime("%d %b %Y", strtotime($row["birthdate"])); $ethnicity = $row["ethnicity"]; $nationality = $row["nationality"]; $homeaddress = $row["homeaddress"]; $province = $row["province"]; $suburb = $row["suburb"]; $hometele = $row["hometele"]; $celltele = $row["celltele"]; $creditclear = $row["creditclear"]; $criminalrecord = $row["criminalrecord"]; $driverslicense = $row["driverslicense"]; $owntransport = $row["owntransport"]; $medicalconditions = $row["medicalconditions"]; $sql = mysql_query("UPDATE cic_candidates SET title='$title', username='$username', surname='$surname', identityno='$identityno', gender='$gender', birthdate='$birthdate', ethnicity='$ethnicity', nationality='$nationality', homeaddress='$homeaddress', province='$province', suburb='$suburb', hometele='$hometele', celltele='$celltele', creditclear='$creditclear', criminalrecord='$criminalrecord', driverslicense='$driverslicense', owntransport='$owntransport', medicalconditions='$medicalconditions' WHERE id='$id'"); echo 'Your account info has been updated, you will now see the new info.<br /><br /> To return to your profile edit area, <a href="edit_personal_details.php">click here</a>'; exit(); } ?>
  2. Im creating a CMS for my site and in my admin page I have an add page that adds new content to my site LOCATED HERE and have added a few form fields. 2 of these are: IMAGE URL (text box) & UPLOAD IMAGE (select file button) When I fill in all the fileds and select an image using IMAGE URL and hit add article, it works fine and my form is saved to my database and is then displayed on my site. When I fill in all the fileds and select an image using UPLOAD IMAGE and hit add article, it adds the image to my selected folder in my cpanel but DOES NOT ADD TO DATABASE. My question is: How can I get it to add to the database? and save the new images location to the image field on the database? I have followed this tutorial when adding the upload file button to my page. Please do not show me links on how to do this as I already have read through them but I stuggle when it comes to adding this to my code. my add.php code is this. <?php session_start(); include_once('../include/connection.php'); if (isset($_SESSION['logged_in'])){ if (isset($_POST['title'], $_POST['content'])) { $title = $_POST['title']; $content = nl2br($_POST['content']); if (!empty($_POST['image'])) { $image = $_POST['image']; } else { $image = $_POST['imageupload']; if (isset($_FILES['imageupload'])) { $errors = array(); $allowed_ext = array('jpg', 'jpeg', 'png', 'gif'); $file_name = $_FILES['imageupload'] ['name']; $file_ext = strtolower (end (explode ('.', $file_name))); $file_size = $_FILES['imageupload'] ['size']; $file_tmp = $_FILES['imageupload'] ['tmp_name']; if (in_array ($file_ext, $allowed_ext) === false) { $errors[] = 'File extension not allowed'; } if ($file_size > 2097152) { $errors[] = 'File size must be under 2mb'; } if (empty($errors)) { if (move_uploaded_file($file_tmp, 'images/'.$file_name)) { echo 'File uploaded'; } }else{ foreach ($errors as $error) echo $error, '<br />'; } } } $link = $_POST['link']; $category = $_POST['category']; $brand = $_POST['brand']; if (empty($title) or empty($content)) { $error = 'All Fields Are Required!'; }else{ $query = $pdo->prepare('INSERT INTO mobi (promo_title, promo_content, promo_image, promo_link, promo_cat, promo_name) VALUES(?, ?, ?, ?, ?, ?)'); $query->bindValue(1, $title); $query->bindValue(2, $content); $query->bindValue(3, $image); $query->bindValue(4, $link); $query->bindValue(5, $category); $query->bindValue(6, $brand); $query->execute(); header('location: index.php'); } } ?> <?php if (isset($_FILES['Filedata'])) { // And if it was ok if ($_FILES['Filedata']['error'] !== UPLOAD_ERR_OK) exit('Upload failed. Error code: ' . $_FILES['image']['error']); $filename = $_FILES['Filedata']['name']; $targetpath = "../img/news/" . $filename; //target directory relative to script location $copy = copy($_FILES['Filedata']['tmp_name'], $targetpath); } ?> <html> <head> <title>Add Article</title> <link rel="stylesheet" href="../other.css" /> </head> <body> <div class="container"> <a href="index.php" id="logo"><b>← Back</b></a> <br /> <div align="center"> <h4>Add Article</h4> <?php if (isset($error)) { ?> <small style="color:#aa0000;"><?php echo $error; ?></small><br /><br /> <?php } ?> <form action="add.php" method="post" autocomplete="off" enctype="multipart/form-data"> <input type="text" name="title" placeholder="Title" /><br /><br /> <textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br /> <input name="imageupload" type="file" id="image" placeholder="Imageupload" /> <input type="text" name="image" placeholder="Image" /><br /><br /> <input type="link" name="link" placeholder="Link" /><br /><br /> <input type="category" name="category" placeholder="Category" /><br /><br /> <input type="category" name="brand" placeholder="Brand" /><br /><br /> <input type="submit" value="Add Article" /> </form> </div> </div> </body> </html> <?php }else{ header('location: index.php'); } ?> please help. thanks.
  3. I want to list results that belong to a certain category. However, I have multiple categories and some results can belong to more than one cateogry. I want to a query that will show all the results from several categories, the number of categories will be aribitrary though. So I will have the categories contained within an array e.g. $cat_ids = array(12,26,32) And I want the query to be $sql = "SELECT * FROM `categories` WHERE `cat_id`=12 OR `cat_id`=26 OR `cat_id`=32"; Of course sometimes there may only be 1 category, and sometimes there could be 5. So how do you execute the array in the query? Or do I have to run a foreach loop? $sql = "SELECT * FROM `categories` WHERE" $i = 0; foreach ($cat_ids AS $cat_id){ if($i!=0) $sql = "OR " $sql = "`cat_id`=$cat_id" $i++ }
  4. I have a setup where the user has the following options: - upload a new image to an existing article that has no existing image - Updating article removing existing image leaving article with no image at all - update article with a new image, replacing old image (delete it). Deleting old image and removing image name in table works. Replacing old image with a new and update table with new image name works. Uploading new image to an article that has no existing image and updating table with new image new works. But, if user only wants to update the article itself, but keep existing image, the old image name is removed in table. I have tried to update table by retrieving old image name and posting it again into the table, shows up blank I have tried to update table removing the code to update the $image_name at all by only updating those that are changed, this also removes the old image name, leaving 'image_name' in table blank. Any idea what could cause this? Here is my code where I have tried to update table with old image name: (The code has been edited as it is part of a file called upload_data.php that also handel 8 other tables for other pages. If the code is missing something, that would be why.. The complete file is attached). require_once 'includes/db_connect.php'; include 'includes/functions.php'; sec_session_start(); if(login_check($mysqli) !== true) { header('Location: ./login.php?login'); exit; } if ($_SESSION['perm'] < 69) //This is the lowest rank that can view the page all ranks above can view but none below. { echo "<script>"; echo "alert(\" Desverre ! Du har ikke rettigheter til å se denne siden!\");"; //Show Message Box echo "</script>"; echo "<script>"; echo "window.location = \"index.php\";"; //Send To Secure Index Page echo "</script>"; exit; } $_GET['pid']; $pid = $_GET['pid']; // Get data from form $content_id = $_POST["content_id"]; $news_priority = $_POST['news_priority']; $layout = $_POST['news_layout']; $news_menu_title = $_POST['news_menu_title']; $news_title = $_POST['news_title']; $news_time = $_POST['news_time']; $myFile = $_FILES['myFile']; $old_image = $_POST['old_image']; $news_image_txt = $_POST['news_image_txt']; $news_content = $_POST['news_content']; $date = $_POST['date']; // Define other options $table = "content_news"; $image = 'news_image'; define("UPLOAD_DIR", "../images/news/"); $imageToDelete = $r["news_image"]; $DirToDeleteIn = '../images/news/'; // Check if file was uploaded if (is_uploaded_file($_FILES['myFile']['tmp_name'])) { $fileCheck = "1"; } else { $fileCheck = "2"; } // If file exists, upload it if ($fileCheck == 1) { // Process file upload include "includes/process_image.php"; // End Process file upload } // END If file exists, upload it // Check if old image if($old_image != NULL) { // Check if it needs to be deleted $checkVars2 = array(4, null); if(in_array($layout, $checkVars2)) { // Delete image if (!unlink($DirToDeleteIn.$old_image)) { // If it failed to delete echo ("OBS! Klarte ikke slette $DirToDeleteIn$old_image , ERROR line 259"); // Pop-up-message echo "<script>"; echo "alert(\"Advarsel! Innholdet ble IKKE oppdatert fordi tilhoereden fil $DirToDeleteIn$imageToDelete heller ikke kunne slettes. Vennlisgt kontakt webmaster for hjelp!\");"; echo "window.location = \"administrate.php?pid=$pid\";"; echo "</script>"; exit; } else { // If file was deleted, show message echo ("Deleted $DirToDeleteIn$old_image"); } } } else { // If there are no old file, check if layout is set wrong. $checkVars3 = array(1, 2, 3); if(in_array($layout, $checkVars3)) { // If layout is set to 1, 2 or 3, check if this is correct by checking if new file is present if($fileCheck == 2) { // No new file was added, layout was set incorectly, fix it. $layout = 4; echo "New layout was set to $layout"; } } } // Check if existing file has to be deleted because if new file // First check if new file has been uploaded if($fileCheck == 1) { // Check if old file exist if($old_image != NULL) { // IF old file exist, delete it // Delete image if (!unlink($DirToDeleteIn.$old_image)) { // If it failed to delete echo ("OBS! Klarte ikke slette $DirToDeleteIn$old_image , ERROR line 259"); // Pop-up-message echo "<script>"; echo "alert(\"Advarsel! Innholdet ble IKKE oppdatert fordi existerende fil $DirToDeleteIn$imageToDelete heller ikke kunne slettes. Vennlisgt kontakt webmaster for hjelp!\");"; echo "window.location = \"administrate.php?pid=$pid\";"; echo "</script>"; exit; } else { // If file was deleted, show message echo ("Deleted $DirToDeleteIn$old_image"); } } } // End check to see if old file has to be deleted because of new file is uploaded. } // Prepeare update DB if($fileCheck == 2) // If new file is not uploaded { if($old_image != NULL) // If old file exists { if($layout != '4') // If layout is set to 1, 2, or 3 { // Update possible imge text and set feedback message for image $updated_image_txt = $news_image_txt; $feedback_on_image = " Er fortsatt " . $old_image; // Update DB with no new image $inputquery = "UPDATE `content_news` SET `news_priority`='$news_priority', `news_layout`='$layout', `news_menu_title`='$news_menu_title', `news_title`='$news_title', `news_time`='$news_time', `news_image`='$old_image', `news_image_txt`='$updated_image_txt', `news_content`='$news_content', `date`='$date' WHERE `news_id`='$content_id'"; // Print UPDATE results $mysqli->query($inputquery); print "<br /><br /><br /><br /><br /><br /><br />\n"; print "$inputquery <br />linje 357\n"; echo "<p>Intet nytt bilde å laste opp</p>"; echo "<script>"; echo "alert(\"Gratulerer! Nyheten er naa endret. Gammelt bilde: $feedback_on_image \");"; echo "window.location = \"administrate.php?pid=$pid\";"; echo "</script>"; if($mysqli->connect_errno) { echo 'OBS! Klarte ikke å endre nyhet. Kontakt webmaster for hjelp. '; } } else // If layout is set to 4 { // Set file name and file text to blank, and set feedback image for file unset($GLOBALS['updated_image_name']); unset($GLOBALS['updated_image_txt']); $feedback_on_image = $old_image . "- Er nå slettet"; // Update DB with no new image $inputquery = "UPDATE `content_news` SET `news_priority`='$news_priority', `news_layout`='$layout', `news_menu_title`='$news_menu_title', `news_title`='$news_title', `news_time`='$news_time', `news_image`='$updated_image_name', `news_image_txt`='$updated_image_txt', `news_content`='$news_content', `date`='$date' WHERE `news_id`='$content_id'"; // Print UPDATE results $mysqli->query($inputquery); print "<br /><br /><br /><br /><br /><br /><br />\n"; print "$inputquery <br />linje 357\n"; echo "<p>Intet nytt bilde å laste opp</p>"; echo "<script>"; echo "alert(\"Gratulerer! Nyheten er naa endret. Gammelt bilde: $feedback_on_image \");"; echo "window.location = \"administrate.php?pid=$pid\";"; echo "</script>"; if($mysqli->connect_errno) { echo 'OBS! Klarte ikke å endre nyhet. Kontakt webmaster for hjelp. '; } } } else { // Set feedback message $feedback_on_image = 'Var ingen.'; } // Update DB with no image and image_txt $inputquery = "UPDATE `content_news` SET `news_priority`='$news_priority', `news_layout`='$layout', `news_menu_title`='$news_menu_title', `news_title`='$news_title', `news_time`='$news_time', `news_content`='$news_content', `date`='$date' WHERE `news_id`='$content_id'"; // Print UPDATE results $mysqli->query($inputquery); print "<br /><br /><br /><br /><br /><br /><br />\n"; print "$inputquery <br />linje 357\n"; echo "<p>Intet nytt bilde å laste opp</p>"; echo "<script>"; echo "alert(\"Gratulerer! Nyheten er naa endret. Gammelt bilde: $feedback_on_image \");"; echo "window.location = \"administrate.php?pid=$pid\";"; echo "</script>"; if($mysqli->connect_errno) { echo 'OBS! Klarte ikke å endre nyhet. Kontakt webmaster for hjelp. '; } } // New file uploaded - update DB with new file name if($old_image) { // Set file name to old image file name $feedback_on_image = $old_image . "- Er nå slettet"; } else { // Set file name to blank $feedback_on_image = 'Var ingen.'; } $inputquery = "UPDATE `content_news` SET `news_priority`='$news_priority', `news_layout`='$layout', `news_menu_title`='$news_menu_title', `news_title`='$news_title', `news_time`='$news_time', `news_image`='$image_name', `news_image_txt`='$news_image_txt', `news_content`='$news_content', `date`='$date' WHERE `news_id`='$content_id'"; // Print UPDATE results $mysqli->query($inputquery); print "<br /><br /><br /><br /><br /><br /><br />\n"; print "$inputquery <br />linje 360\n"; echo "<p>Nytt bilde ble lagret som " . $image_name . " til mappe: .</p>"; // Check if DB was updated if($mysqli->connect_errno) { echo 'Feil! Klarte ikke å oppdatere nyhet med nytt bilde i databasen. Kontakt webmaster. '; } else { // Pop-up-message echo "<script>"; echo "alert(\"Gratulerer! Nyheten er naa oppdatert med nytt bilde " . $image_name . "! Gammelt bilde: $feedback_on_image\");"; echo "window.location = \"administrate.php?pid=$pid\";"; echo "</script>"; } // END check if DB was updated update_data.php
  5. I would like to solve this query. Query: $sql = 'SELECT DISTINCT *, c.ci as c_i FROM `GSM_cellule` c '. 'LEFT JOIN '.$table_freq.' f ON(c.nidtint=f.nidtint) '. 'WHERE c.NAP_'.$site->ur().' =\'1\' '. $this->_in.' and '.$this->_inetatbdespec.' and '.$this->_inindus.' GROUP BY c.nidtint ORDER BY c.nidtint '; Error: Thanks in advanced.
  6. This code is to let user add a new record <form action="processAdd.php" method="post"> <tr><td></td><td><input type="text" placeholder="Last Name" name="lname" value="" required></td></tr></br> <tr><td></td><td><input type="text" placeholder="First Name" name="fname" value="" required></td></tr></br> <tr><td></td><td><input type="text" placeholder="Course" name="course" value="" required></td></tr></br> <tr><td colspan=2><input type="submit" name="submit" value="Submit"></td></tr> </form> The codes below is where the user inputs are being processed. But I don't want a duplicate record of the last name and the first name. I can always do that by altering the table I've created in the database and set it to UNIQUE so that no similar record can be inserted. But what I wanna do is when the user inputs a similar records (i.e. last name and firt name) it will display an error message. I don't know what's wrong with my codes, it doesn't display a syntax error though when I run it, but it keeps on adding similar records on my database. I've tried the <?php session_start(); $dbconnect = mysql_connect("localhost","root",""); $db = mysql_select_db("web", $dbconnect); $sql = mysql_query("SELECT * FROM tbl_student WHERE stud_laneme = '".$_POST["lname"]."' AND stud_fname = ".$_POST["fname"]."',"); $result = mysql_query($sql); if(mysql_num_rows($result) > 0) { echo "Record already exists"; } else { $sql="INSERT INTO `web`.`tbl_student`( `stud_id`, `stud_lname`, `stud_fname`, `stud_course` ) VALUES( NULL, '".$_POST["lname"]."', '".$_POST["fname"]."', '".$_POST["course"]."' )"; $result = mysql_query($sql); header("location:displayRecord.php"); } ?>
  7. I am working on phpmyadmin. i want to create a system in which users will select 10 players from pool of players and gain points from those 10 players, just like fantasy football. So my first solution was tables: users(name,details,team[10],points gained) and players(name,details,points gained by individual player); but i am not sure how to get that team array in users table. so i searched for solutions, then somesone suggested about creating one more table team and some thing about foreign keys. But still i am confused how to do this? and 1 more question should i use phpmyadmin or mysql workbench to do this . right now i have both installed on system but i have never used mysql workbench. pls help. Thanks
  8. Hey, I want to list all of my database entries to a nice html format. For every unique id there is one row displayed out from my database to my php/html. I just don't know how to do that. I tried using while loop and foreach I just don't know how to properly structure them... My query and php code looks like this: $query = mysql_query("SELECT * FROM sport"); while($row = mysql_fetch_array($query)) { $result = $row['sport_ime'].' '.$row['sezona']; }
  9. Hello, I'm trying to unserialize a string and then compare it and if listed mark the checkbox as CHECKED. It works fine as long as I have 1,2,3,4 checked but if I do something like 1,4 then it only shows 1 as being CHECKED Any help would be appreciated. Thanks in advance. function getm($id) { $query3 = "select memtype from offer WHERE id = '".$id."'"; $result3 = mysql_query ($query3) or die ("Query failed"); $line3 = mysql_fetch_array($result3); $memtype = $line3["memtype"]; $mydata = unserialize($memtype); echo '<tr bgcolor=#CCCCCC><td>'; echo 'Show to:</td><td>'; if(!empty($mydata)) { foreach( $mydata as $key => $value) { $gamenames[] = $key; } } $getaccountinfo = mysql_query("Select id, mem_name, mem_rank from `memtype` WHERE mem_enabled=1 ORDER BY id ASC"); for ($j = 0; $j < mysql_num_rows($getaccountinfo); $j++) { $offerid = mysql_result($getaccountinfo, $j, "id"); $memname = mysql_result($getaccountinfo, $j, "mem_name"); echo(" $gamenames[$j] <input type=checkbox name=memtype[$offerid] value=$offerid"); if($gamenames[$j]==$offerid){echo(" CHECKED");} echo(">$memname <br>"); } echo '</td></tr>'; } $sql = mysql_query("SELECT * FROM offer"); echo '<table border=0><tr><td>'; while($oto = mysql_fetch_array($sql)) { if($count==1) { echo "</td><td>"; $count=0; } $count++; ?> <h3 align=center>OFFER <?php echo $oto['id']; ?></h3> <form method="POST"> <input type="hidden" name="action" value="updateoffer"> <input type="hidden" name="id" value="<?php echo $oto['id']; ?>"> <table border=0 cellpadding=5 bgcolor=#000000> <tr bgcolor=#CCCCCC><td>Price:</td><td>$<input type="text" name="price" value="<?php echo $oto['price']; ?>"></td></tr> <tr bgcolor=#CCCCCC><td>Commission:</td><td>$<input type="text" name="pdcommission" value="<?php echo $oto['pdcommission']; ?>"></td></tr> <tr bgcolor=#CCCCCC><td>Show after login:</td><td><input type="radio" name="enable" value="1"<?php if($oto['enable'] == 1) echo " CHECKED"; ?>> yes <input type="radio" name="enable" value="0"<?php if($oto['enable'] == 0) echo " CHECKED"; ?>> no</td></tr> <?php $showm=getm($oto['id']); ?> <tr><td colspan="2" align="center"><input type="submit" value="Update"></td></tr> </table> </form> <?php } echo '</td></tr></table>'; ?>
  10. I need to develop Feedback module in PHP/MySQL. I would like to know the database design and flow to manage this system. There are questions for 2 tools which i need to store in my databse and need to create report like %of Positive Response, % of Negative Response, No. of Users for Tool1/2 etc. It would be great if i have any similar example/code/link etc. Thanks in advanced for your input. Tool 1 1.Are you satisfied with the performance of the tool ? Yes/No 2.Are you satisfied with the support provided? Yes/No IF NO, Why ? 3.If you need to improve, they are the three major changes you propose Yes/No IF Yes, -----****---- 4.What are the general points (up to 3) that you would like to improve on the project Yes/No IF Yes, -----****---- Tool 2 1.Are you satisfied with the performance of the tool ? Yes/No 2.Are you satisfied with the support provided? Yes/No IF NO, Why ? 3.If you need to improve, they are the three major changes you propose Yes/No IF Yes, -----****---- 4.What are the general points (up to 3) that you would like to improve on the project Yes/No IF Yes, -----****----
  11. I have the following php code that produces some multiple choice questions with each answer per question giving different points. <?php $done = $_POST['done']; if ($done < '1' ) { ?> <form action="quiz.php" method="post" /> How many domains do you own? </BR> <input type="radio" name="op1" value="0"> I don't <BR/><input type="radio" name="op1" value="5"> 1 <BR/><input type="radio" name="op1" value="10"> 2 <BR/><input type="radio" name="op1" value="15"> 3 <BR/><input type="radio" name="op1" value="20"> 4 <BR/><input type="radio" name="op1" value="30"> 5 or more <BR><BR> Do you use skype? </BR> <input type="radio" name="op2" value="1"> Yes <BR/><input type="radio" name="op2" value="0"> No </BR></BR> How many people are currently in your Skype contact list? </BR> <input type="radio" name="op3" value="1"> less than 5 <BR/><input type="radio" name="op3" value="2"> 5 to 10 <BR/><input type="radio" name="op3" value="3"> 11 to 15 <BR/><input type="radio" name="op3" value="4"> 15 to 30 <BR/><input type="radio" name="op3" value="5"> more than 30 <BR><BR> <input type="hidden" name="done" value="1"/> <input type="submit" value="Submit...."/> </form> <?php } else { $score1=$_POST['op1']; $score2=$_POST['op2']; $score3=$_POST['op3']; $total = $score1 + $score2+ $score3; print "Your score Is " . $total . "!"; } ?> </div> I am trying to modify the code so i can make it work with a database i have.This is the structure of the table question which also includes the answers and the points of each answer. que_id | test_id | que_desc | ans1 | ans2 | ans3 | ans4 | true_ans | type | points1 | points2 | points3 | points4 | And this is what i have done so far: <?php session_start(); require_once('config.php'); include 'dbconnect.php'; include 'functions.php'; extract($_POST); extract($_GET); extract($_SESSION); if(isset($subid) && isset($testid)) { $_SESSION[sid]=$subid; $_SESSION[tid]=$testid; header("location:$self_page?page=kinder.php"); } ?> <?php $rs=mysql_query("select * from question where test_id=20",$conn) or die(mysql_error()); $i=0; while($row = mysql_fetch_array($rs)) { $i++; $id = $row["id"]; $question = $row["que_desc"]; $opt1 = $row["ans1"]; $opt2 = $row["ans2"]; $opt3 = $row["ans3"]; $opt4 = $row["ans4"]; $score1= $row['points1']; $score2= $row['points2']; $score3= $row['points3']; $score4= $row['points4']; $answer = $row["true_ans"]; echo "$question<br>"; echo "<input type='radio' id='radio1' name='$i' value='$opt1'/><label for='radio1'>$opt1</label><br>"; echo "<input type='radio' id='radio1' name='$i' value='$opt2'/><label for='radio1'>$opt2</label><br>"; echo "<input type='radio' id='radio1' name='$i' value='$opt3'/><label for='radio1'>$opt3</label><br>"; echo "<input type='radio' id='radio1' name='$i' value='$opt4'/><label for='radio1'>$opt4</label><br>"; echo "<br>"; } ?> <center> <input type="hidden" name="done" value="1"/> <input type="submit" value="Submit...."/> </center> </form> <?php } else { $total = ........... } ?> </div> </body> My question is how to pass each answer points using the While loop i have above and how to calculate the total score.
  12. hi i would like to have my css test box attached to the side of the box like it is on the second picture ... any way to do it ? #socialbox { background-color: #FFF; padding: 7px; height:200px; width:35px; border: 1px solid #DBDBDB; -moz-border-radius:5px; -webkit-border-radius:5px; border-radius:5px; -webkit-box-shadow: #E4E4E4 0px 0px 5px; -moz-box-shadow: #E4E4E4 0px 0px 5px; box-shadow:#E4E4E4 0px 0px 5px; margin-bottom: 5px; /* max-width:50px; max-height:100px; */ float:right; margin-right:180px; }
  13. I am trying to update 3 images of same product_id. I have a different product_table and Product_images table. The product_images table has 5 fields; image_id, product_id, name, images, ord. I am trying to update images for any specific product_id. The problem I was facing before was that it set the same 'Image' for all of the three 'images', that why I add 'ord' filed and it solver that problem. Now I have a new problem. I am unable to understand where to write update image' query. If I write it inside for loop then it runs 'Update Query' 6 times and if I write it outside for loop then its unable to find out $ord[] variable. Kindly tell the way to resolve this problem. Given below is the part of code I am working on. /* * ------------------- IMAGE-QUERY Test 002 -------------------- */ if (isset ( $_FILES ['files'] ) || ($_FILES ["files"] ["type"] == "image/jpeg")) { $i = 1; /* * ----------------------- Taking Current Order_id ------------------------ */ // $order_sql= "select MAX(ord) from product_images"; $order_sql = "SELECT ord from product_images where product_id=$id"; $order_sql_run = mysql_query ( $order_sql ); echo mysql_error (); for($i = 1; $i <= $order_fetch = mysql_fetch_array ( $order_sql_run ); $i ++) // while ($order_fetch= mysql_fetch_array($order_sql_run)) {) echo 'ID ' . $order_id [$i] = $order_fetch [(ord)]; } /* * ----------------------- Taking Current Order_id ------------------------ */ foreach ( $_FILES ['files'] ['tmp_name'] as $key => $tmp_name ) { // echo $tmp_name."<br>"; // echo 'number<br>'; echo $image_name = $_FILES ["files"] ["name"] [$key]; $random_name = rand () . $_FILES ["files"] ["name"] [$key]; $folder = "upload/products/" . $random_name; move_uploaded_file ( $_FILES ["files"] ["tmp_name"] [$key], "upload/products/" . $random_name ); echo '<br>'; echo $sql = "update product_images set name= '$random_name',images= '$folder' where product_id=$id andord=$order_id[$i]"; if ($query_run = mysql_query ( $sql )) { echo '<br>'; echo 'Done'; } else { echo mysql_error (); } // $i=$i+1; } } /*------------------- IMAGE-QUERY Test 002 --------------------*/
  14. Hi all, Thank you for viewing my post. In my application I allow users to draw shapes on google maps using google maps api v3. I dont know how to store the polygons in MySQL? Im new to google maps api and dont have a clue. Please help. I was thinking should I store each point seperately in a database field or store the whole polygon as json? This is what I have so far. I have created a json object that stores all the verticles in a list. I was thinking of saving this whole json in one database field? This is the code used to contruct the array: var vertices = selectedShape.getPath(); // MVCArray var pointsArray = []; //list of polyline points for (var i =0; i < vertices.getLength(); i++) { var xy = vertices.getAt(i); //LatLang for a polyline var item = { "lat" : xy.lat(), "lng":xy.lng()}; pointsArray.push(item); } var polygon = {"points" : pointsArray}; This is the constructed json result: {"points": [ {"lat": 51.51814351604911, "lng": -0.14479637145996094 }, { "lat": 51.51830374452608, "lng": -0.13861656188964844}, { "lat": 51.516194024429446, "lng": -0.13968944549560547} ]} Should I have the whole thing in one field? Is it better to save each vertices (lat and lng) in a seperate row, so for the above polygon there will be 3 rows? Kind regards, Imran
  15. I have the following query that gives me the result i want. In a nutshell it searches two columns to find the max value in each of these two columns and returns the sum of these two values. When i try to pass it to a variable in php it doesn't seem to work. I want to be able to pass the sum in a variable so i can use the variable later into an IF Condition. For example: if ($scoremax >= '160') { code here } Here is my query: select (max(scoreioa) + max(scoreioa2)) from result where username='username' and here is the php code: $maxscore = mysql_query("select (max(scoreioa) + max(scoreioa2)) from result where username='username'"); mysql_data_seek($maxscore, $scoremax); $row = mysql_fetch_row($maxscore); $scoremax = $row[0];
  16. I have two tables Table 1 -mdl_question_attempts id questionid rightanswer responsesummary 1 1 A A 2 1 A B 3 1 A A 4 1 A B 5 2 A A 6 1 A A 7 2 D E 8 2 D D 9 2 D E 10 3 F F 11 3 F G Table 2 - mdl_question_attempt_steps id questionattemptid userid 5 1 1 6 2 1 7 3 2 8 4 1 9 5 2 10 6 1 11 7 1 12 8 1 13 9 1 14 10 1 15 11 1 Table 1 -mdl_question_attempts, primary key –“id” field is related with Table 2 - mdl_question_attempt_steps , foreign key –“questionattemptid” Table 1 is about users answers for certain questions. “rightanswer”-is the correct answer for a particular question and “responsesummary” is the answer given by user for that question. “questionid” represent the question no. Sometimes same user tried one question several times and their answer in each attempts shows in table 1. For each question “userid” or user can be found from Table 2 Eg:1st row in table1 done by userid =1 So my question is I want to find percentage or ratio of times a learner(one user-eg:userid =1) answers the same question twice wrong, based on the number of times a learner answered a question twice? Highlighted ones in the table 1 shows the userid=1 related data User1 answered question 1 – 4 times and it is 2 times wrong User1 answered question 2 – 3 times and it is 2 times wrong Question 3 is answered 2 times and only 1 time wrong. So I want same question twice wrong. Therefore Question 3 is not considered questionid wrong count 1 2/4 2 2/3 So my final output for the userid=1 is =((2/4)+(2/3))/2 =0.583 =summation of wrong count divided by average or that is 2 times (only 2 questioned answerd) If 3 question answered summation should be divided by 3. I wrote following three codes and I can get the output separately. But I want to get this in one query function quiztwicewrong() { $con=mysqli_connect("localhost:3306","root","", "moodle"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //quiz twice wrong //query 1 $resultq = mysqli_query ($con,"SELECT mdl_question_attempts.rightanswer as rightanswer,count(mdl_question_attempts.questionid) as questionid1 FROM mdl_question_attempts,mdl_question_attempt_steps WHERE mdl_question_attempt_steps.questionattemptid=mdl_question_attempts.id and mdl_question_attempt_steps.userid='1' and mdl_question_attempts.rightanswer<>mdl_question_attempts.responsesummary GROUP BY mdl_question_attempts.questionid HAVING questionid1>1 ") or die("Error: ". mysqli_error($con)); while($rowq= mysqli_fetch_array( $resultq)) { echo $rowq['questionid1']."-".$rowq['rightanswer']."<br>"."<br>"."<br>"; } //query 2 $resultqall = mysqli_query ($con,"SELECT mdl_question_attempts.rightanswer as rightanswer,count(mdl_question_attempts.questionid) as questionid1 FROM mdl_question_attempts,mdl_question_attempt_steps WHERE mdl_question_attempt_steps.questionattemptid=mdl_question_attempts.id and mdl_question_attempt_steps.userid='1' GROUP BY mdl_question_attempts.questionid HAVING questionid1>1") or die("Error: ". mysqli_error($con)); while($rowqall= mysqli_fetch_array( $resultqall)) { echo $rowqall['questionid1']."-".$rowqall['rightanswer']."<br>"."<br>"."<br>"; } //query 3 $resultqdup = mysqli_query ($con,"SELECT count(*) as duplicate FROM (select mdl_question_attempts.rightanswer as rightanswer from mdl_question_attempts,mdl_question_attempt_steps WHERE mdl_question_attempt_steps.questionattemptid=mdl_question_attempts.id and mdl_question_attempt_steps.userid='1' and mdl_question_attempts.rightanswer<>mdl_question_attempts.responsesummary GROUP BY mdl_question_attempts.questionid HAVING COUNT(mdl_question_attempts.questionid)>1) as questionid1 ") or die("Error: ". mysqli_error($con)); while($rowqdup= mysqli_fetch_array( $resultqdup)) { echo $rowqdup['duplicate']; } mysqli_close($con); } return quiztwicewrong(); Outputs from the 3 queries are query 1- ouput 2-A 2-D query 2- ouput 4-A 3-D 2-F (I don’t want this part-this comes for the 3rd question, but I want only the output related to query 1- ouput,only answer more than 1 time wromg) query 3- ouput 2 So I want to combine 3 output and need to calculate and get the value =((2/4)+(2/3))/2 =0.583 Please help me to do this by editing my code or any suggestion please?
  17. Hi, I have cobbled together the code from two tutorials, both of which work superbly on their own, but I must have something wrong in the code because together they don't work. I have a database of chillies which is searchable. I want to add pagination when the results returned exceed 10. The problem is the first page of results returns 10 as it should, and at the bottom of the page there is the option to go to page two or next, but when you do, page 2 has no results and when you return to page one there are no results either. The code is as follows; <h1>Chilli Search Results</h1> <?php // Initilise search output variable $search_output = ""; // Process the search query if(isset($_POST['searchquery'])) { // Filter user input $searchquery = preg_replace('#[^a-z 0-9?]#i', '', $_POST['searchquery']); $heat = $_POST['heat']; // Select Database mysql_select_db("allotmen_content") or die (mysql_error()); if($heat != 'any'){ $sqlcommand = "SELECT id, image1, common_name, url, url_short FROM chillies WHERE common_name LIKE '%$searchquery%' AND heat = '$heat'"; }else{ $sqlcommand = "SELECT id, image1, common_name, url, url_short FROM chillies WHERE common_name LIKE '%$searchquery%'"; } $query = mysql_query($sqlcommand) or die(mysql_error()); $count = mysql_num_rows($query); if(empty($_POST['searchquery'])) { // If search box is empty echo 'Search box can not be empty. Please go back and enter some text <a href="chillies-homepage.php">BACK</a> <br /><br />'; // If count is greater than 0 }else if($count > 0) { $search_output .= "<hr /> $count Results for <strong>$searchquery</strong><hr /><br /><br />"; if (isset($_GET['pn'])) { // Get pn from URL vars if it is present $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new) //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated) } else { // If the pn URL variable is not present force it to be value of page number 1 $pn = 1; } //This is where we set how many database items to show on each page $itemsPerPage = 10; // Get the value of the last page in the pagination result set $lastPage = ceil($count / $itemsPerPage); // Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage if ($pn < 1) { // If it is less than 1 $pn = 1; // force if to be 1 } else if ($pn > $lastPage) { // if it is greater than $lastpage $pn = $lastPage; // force it to be $lastpage's value } // This creates the numbers to click in between the next and back buttons // This section is explained well in the video that accompanies this script $centerPages = ""; $sub1 = $pn - 1; $sub2 = $pn - 2; $add1 = $pn + 1; $add2 = $pn + 2; if ($pn == 1) { $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> '; } else if ($pn == $lastPage) { $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> '; $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> '; } else if ($pn > 2 && $pn < ($lastPage - 1)) { $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> '; $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> '; } else if ($pn > 1 && $pn < $lastPage) { $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> '; $centerPages .= ' <span class="pagNumActive">' . $pn . '</span> '; $centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> '; } // This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query $limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage; // Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax // $sql2 is what we will use to fuel our while loop statement below $sql2 = mysql_query("$sqlcommand ORDER BY common_name ASC $limit"); $paginationDisplay = ""; // Initialize the pagination output variable // This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display if ($lastPage != "1"){ // This shows the user what page they are on, and the total number of pages $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. ' '; // If we are not on page 1 we can place the Back button if ($pn != 1) { $previous = $pn - 1; $paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> '; } // Lay in the clickable numbers display here between the Back and Next links $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>'; // If we are not on the very last page we can place the Next button if ($pn != $lastPage) { $nextPage = $pn + 1; $paginationDisplay .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> '; } } while($row = mysql_fetch_array($sql2)) { $id = $row["id"]; $image = $row["image1"]; $title = $row["common_name"]; $url = $row["url"]; $url_short = $row["url_short"]; $search_output .= "<a href=\"$url_short\"><img src=\"images/$image\" width=\"100px\" height=\"100px\"/></a> $title - $url <br /><br />"; } // Close while // If no results are found } else { $search_output = "<hr /><br /> Sorry, there are no results for <strong>$searchquery</strong>. <br /><br />Try entering <strong>$searchquery</strong> again but this time select <strong>'ANY HEAT'</strong> as the Heat Level<br /><br /><hr />"; } } ?> <?php echo $search_output; ?> <br /> <?php echo $paginationDisplay; ?> I'm guessing I have have something not quite right, I just can't see it. The page itself can been seen here http://www.allotment-web.org/chillies-homepage.php Search just the letter 'a' to bring more than 10 results and you'll see the issue. There seems little point increasing the number of varieties until I fix this pagination. Any help greatly appreciated. Richard
  18. when i am selecting a answer in a radio button of four options it only compares first option of all the options , the will have to see which answer is selected and verify that selected answer is correct or not and display corect if correct and display wrong if wrong example go to this link http://www.naveenr5.5gbfree.com/quiz.php?question=4 There are two tables named questions and answers questions table is questions table is id question_id question 1 1 question1 2 2 question2 answers table is id question_id answer correct 1 1 answer1 0 2 1 answer2 1 3 1 answer3 0 4 1 answer4 0 same for second question the php code iam using is here session_start(); require_once("scripts/connect_db.php"); $arrCount = ""; if(isset($_GET['question'])){ $question = preg_replace('/[^0-9]/', "", $_GET['question']); $output = ""; $answers = ""; $q = ""; $dv=""; $dv2=""; $singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question' LIMIT 1"); while($row = mysql_fetch_array($singleSQL)){ $id = $row['id']; $thisQuestion = $row['question']; $type = $row['type']; $subject =$row['subject']; $exam =$row['exam']; $explan =$row['explan']; $question_id = $row['question_id']; $s ='<strong>'.$subject.'</strong>'; $e ='<small>'.$exam.'</small>'; $q = '<h2>'.$thisQuestion.'</h2>'; $ex ='<div id="welcomeDiv" style="display:none;" class="expl" >'.$explan.'</div>'; $sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()"); while($row2 = mysql_fetch_array($sql2)){ $id2=$row2['id']; $answer = $row2['answer']; $correct = $row2['correct']; $answers .= '<table class="table table-hover table-bordered"> <tr> <td class="chk"><label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label></td> </tr></table> <input type="hidden" id="qid" value="'.$id.'" name="qid"><br /> '; $result=mysql_query("SELECT id FROM answers WHERE question_id='$question' "); $nrows=mysql_num_rows($result); for($i=0;$i<=4;$i++){ if (isset($_POST[$correct])) { $answer= $_POST[$correct]; } if($answer&&$correct==1){ echo $dv.='<div style="display:none;" class="green" id="chek" >Your answer '.$answer.' is correct</div>';} else{ echo $dv2.='<div style="display:none;" class="red" id="chek" >Your answer '.$answer.' is worng</div>';} } } $output = ''.$s.','.$e.''.$q.','.$dv.''.$dv2.''.$answers.''.$ex.'<input type="button" name="answer" value="check" onclick="showDiv();chk();"/> <span ><button onclick="post_answer()" class="btn" >Submit</button></span>'; echo $output; } }
  19. Hi...., I would like to view the Unicode characters in my website. When i retrieves the value from database, it show "?????????????". How could i be able to debug this error.
  20. hey, this should echo all of the results from the query, right? in the database there is more than 1 fields to echo, but it only echos 1, whats wrong with it? $getid = mysql_query("SELECT * FROM $tbl_name WHERE userid='$id'", $connect); $idresults= mysql_fetch_array($getid); while($idresults= mysql_fetch_array($getid)){ echo $idresults['frienduserid']; }
  21. hello i'm creating an ajax chat system and everything is working fine but the problem, i'm facing is that i can't replace some part of the message with the emotion kept in the array... If i run only the emotion script then its working fine but i can't immplement with the chat system.. Any body plz help... <?php ob_start(); session_start(); ?> <style> body{ background-color: grey; } #box{ width: 326px; height: 432px; border: 1px solid activeborder; margin: 0px auto; } #box1{ width: 326px; height: 400px; background-color: #eee; margin-bottom: 10px; } </style> <form method="post" action=""> <div id="box"> <div id="box1"> <?php mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db(chat) or die(mysql_error()); $req = mysql_query("SELECT * FROM msg") or die(mysql_error()); while($row = mysql_fetch_array($req)){ $m = $row['message']; echo "<div id='message'> $m </div>"; } ?> </div> <input type="text" id="chat" size="50" /> <input type="button" name="submit" value=" Chat " onclick="sendmessage()" /> </div> </form> <script> function sendmessage() { var msg = document.getElementById("chat").value; var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("box1").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","chat_msg.php?m="+msg,true); xmlhttp.send(); } </script> and the chat_msg.php code is <?php session_start(); mysql_connect("localhost","root","") or die(mysql_error()); mysql_select_db(chat) or die(mysql_error()); $sess = session_id(); $mg = $_REQUEST['m']; $sql = mysql_query("INSERT INTO msg VALUES('','$sess','$mg')") or die(mysql_error()); $req = mysql_query("SELECT * FROM msg") or die(mysql_error()); while($row = mysql_fetch_array($req)){ $m = $row['message']; echo "<div id='message'> $m </div>"; } ?> and the emotion code is $str = $_REQUEST['comment']; $emo = array("<3", "#12", "@153", "#45", "@352"); $img = array("<img src='emotions/1.png' height='113' width='120' alt='ugly' />", "<img src='emotions/2.png' height='113' width='120' alt='happy' />", "<img src='emotions/3.png' height='113' width='120' alt='love' />", "<img src='emotions/4.png' height='113' width='120' alt='sweet' />", "<img src='emotions/5.png' height='113' width='120' alt='smiley' />"); $new_str = str_replace($emo, $img, $str); echo "<hr />"; echo $new_str; } ?> i can;t figure where to put the emotion code so that it will work like facebook chat system. Any help will be greatly appreciated... Thank u.
  22. Hello: Any PHP MYSQL experts out there willing to help? I would greatly appreciate it. I built a web directory using WordPress Platform and I am trying to PULL data from my database and display it on the home page. I have the following code: $sql = "SELECT * FROM `agents` LIMIT 0, 30 "; I know this isn't much to work with but I am happy to answer any question related to my tables. Regards, John.
  23. $Database = new $DatabaseClass; $Database->Connect($_POST["host"], $_POST["username"], $_POST["password"], $_POST["database"]); $Database->Update($URL . "messages", "`status`='1'", "`index`='$Index'"); //status and index is INT and everything else is TEXT $Database->Disconnect(); if ($Database->Connect($_POST["host"], $_POST["username"], $_POST["password"], $_POST["database"]) == true) $Access = "Allowed"; $Database->Update($_POST["table"], "lastlogin='" . date("n/j/Y") . "'", "username='" . $_POST["username"] . "'"); //Everything is TEXT $Database->Disconnect(); Both of these code snippets work but I want to know why when I use the update query on the second piece of code I don't need single quotations around anything but I must have them around the first piece of code for it to work at all. Also when I try to use the first piece of code again to change status to a different value with the exact same code it does not work. // This is met when the file redirects to itself via a from submit and passes the following values via POST. This does not work. else if ($_POST["action"] == "delete") { $Database->Connect($_POST["host"], $_POST["username"], $_POST["password"], $_POST["database"]); $Database->Update($URL . "messages", "`status`='2'", "`index`='" . $_POST["deleteindex"] . "'"); //Does not work. $Database->Disconnect(); } I made sure I was able to connect to my SQL database with each snippet of code but I am not able to call the update query consistently. I am also sure that the values I passed in were corrected when I echoed them out.
  24. hi all , I have a table that shows all rows of a selected table . problem is that I want to delete marked rows from this table but this code is not working for me . updating code works fine but I can't delete selected rows . <? if($_SESSION["count"]!=0){ ?> <!-- begining of setting levels informations --> <form name="form2" method="POST" dir="rtl" action="" style="font-family:'B_yekan';"> <input name="level" type="hidden" value="<? if(isset($_POST['level'])){ echo $_POST['level'];} ?>"/> <div align="center" width = 615> <table class="styled-table" cellspacing="0" width="800" border="1"> <tr> <th width="10" scope="col" ></th> <th width="60" scope="col">level</th> <th width="60" scope="col">time</th> <th width="60" scope="col">date</th> <th width="42" scope="col">status</th> <th width="54" scope="col">price</th> <th width="42" scope="col">off</th> <th width="54" scope="col">off 2</th> <th width="60" scope="col">mark</th> </tr> <?php $id = array(); while($rows=mysql_fetch_array($result)){ $id[]=$rows['id']; ?> <tr> <td align="center"><input class="styled-input" type="hidden" name="id[]" id="id" value= "<? echo $rows['id']; ?>" /></td> <td align="center"><input class="styled-input" type="lev" name="lev" id="lev" value="<? echo $tbl_name; ?>" /></td> <td align="center"><input class="styled-input" type="text" name="time[]" id="time" value= "<? echo $rows['time']; ?>" /></td> <td align="center"><select class="styled-input" type="text" name="date[]" id="date" /> <option selected="selected" value="<? if($rows['date']=="1"){echo "1";}else{echo "0";}?>"> <? if($rows['date']=="1"){echo "even";}else{echo "odd";}?></option> <option value="<? if($rows['date']=="1"){echo "0";}else{echo "1";}?>"> <? if($rows['date']=="1"){echo "odd";}else{echo "even";}?></option> </select></td> <td align="center"><select class="styled-input" type="text" name="act[]" id="act" > <option selected="selected" value="<? if($rows['act']==1){echo "1";}else{echo "0";}?>"> <? if($rows['act']==1){echo "enable";}else{echo "disable";}?></option> <option value="<? if($rows['act']==1){echo "0";}else{echo "1";}?>"> <? if($rows['act']==1){echo "disable";}else{echo "enable";}?></option> </select></td> <td align="center"><input class="styled-input" type="text" name="price[]" id="price" value= "<? echo $rows['price']; ?>" /></td> <td align="center"><input class="styled-input" type="text" name="offprice[]" id="offprice" value= "<? echo $rows['offprice']; ?>" /></td> <td align="center"><input class="styled-input" type="text" name="off2price[]" id="off2price" value= "<? echo $rows['off2price']; ?>" /></td> <td align="center"><input class="styled-input" style="padding: 5px;width:20px" type="checkbox" name="checkbox[]" id="checkbox[]" /></td> </tr> <?php }//end of loop ?> </table> </div> <input class="styled-button-8" type="Submit" value="submit" name="Submit" /> <input class="styled-button-8" type="Submit" value="delete" name="delete" /> <?php }//end of if ?> </form> <?php // Check if button name "Submit" is active, do this if(isset($_POST['Submit']) && $_POST['Submit'] == 'submit') { for($i=0;$i<$_SESSION["count"];$i++) { $sql1="UPDATE `".$tbl_name."` SET `time`='".$_REQUEST['time'][$i]."',`date`='".$_REQUEST['date'][$i]."',`act`='".$_REQUEST['act'][$i]."' , `price`='".$_REQUEST['price'][$i]."' , `offprice`='".$_REQUEST['offprice'][$i]."', `off2price`='".$_REQUEST['off2price'][$i]."' WHERE `id`='".$_REQUEST['id'][$i]."' "; $result1=mysql_query($sql1); } if(isset($result1)){ $_SESSION["count"]=""; ?> <script language="javascript">alert('all of the rows updated successfully');</script> <?php print(redirect('regmanage.php')); } ?> <!-- deleteing records --> <?php // Check if button name "Submit" is active, do this if(isset($_POST['delete']) && $_POST['delete'] == 'delete') { for($i=0;$i<$_SESSION["count"];$i++) { if(isset($_POST['checkbox'][$i])){ $del_id = $_POST['checkbox'][$i]; $sql1 = "DELETE FROM `".$tbl_name."` WHERE `id`='".$_REQUEST['id'][$i]."' "; $result1= mysql_query($sq1) or die(mysql_error()); } } } if(isset($result1)){ ?> <script language="javascript">alert('the selected row deleted successfully.');</script> <?php print(redirect('regmanage.php')); } ?> <!-- end of setting infromations -->
  25. I am a newbie and I am in need of some help. Currently, I have a email being piped to a program via cpanel "forwarder" advance tap. The parsing seeems to be doing its function but I cannot get it to insert the data into the table. HEre is hte code prior to insert. Can someone help me understand how to write this correct. The idea is that for every new alert extract the date, then insert in to the table. yOU help would be appreciated! $sql = "INSERT INTO `LOG_TABLE` (`Type`, `Symbol`, `Score`, `Timestamp`) VALUES "; foreach($alerts as $alert) { preg_match("!^Alert[1-9]+ \((MRI|QT)\):<br />(.*?)$!i", trim($alert), $m); $stocks = explode(", ", trim($m[2])); foreach($stocks as $stock) { list($symbol, $score) = explode(":", $stock); $sql .= "('".$m[1]."', '".$symbol."', '".$score."', FROM_UNIXTIME(now()), "; } } $sql = trim($sql, " ,"); if ( ! empty($sql) ) mysqli_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS); mysqli_select_db(DB); mysqli_query($sql)or die(mysql_error()); } exit(0);
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.