PHP - How To Retrieve A Primary Key
I have a form that ask user to enter other details but the primary key as this is automated and when they click on Submit button it takes the user to different form. now on this form I would like to retreive the primary that has just been added to the table. How can I do this?
Similar TutorialsIf I am using this: Code: [Select] mysql_query("INSERT INTO M1QuizResults (Email, Q1Choice, Q2Choice, Q3Choice, Score, Pass, Date_Taken, Time_Taken) VALUES(' " . $_SESSION['Email'] . " ', '$QChoice_1', '$QChoice_2', '$QChoice_3', '$Score', '$Pass', CURDATE(), NOW())") or die(mysql_error()); What would I use to find out what the row's "Id" is? "Id" is my primary key. I want to store this "Id" as a session variable. thanks! I can't figure out where this is going wrong. But it obviously has to do with the primary key for the table. Here is the code: //set led request if ( isset ( $action ) && $action == 'submit_led_request' ) { $order_id = $_GET['order_id']; $products = explode(',', $_GET['product']); $qty = explode(',', $_GET['qty']); //make sure the same of number of records exist in each array if ( count ( $products ) == count ( $qty ) ) { $original_request_id = $pdo->query("SELECT MAX(id) FROM leds_requests LIMIT 1")->fetch(PDO::FETCH_NUM)[0] + 1; for ( $i = 0; $i <= count ( $products ) - 1; $i++ ) { $query = "INSERT INTO leds_requests (original_request_id, order_id, user_id, product_id, qty, status_id) VALUES (:original_id, :order_id, :user_id, :product_id, :qty, 0)"; $statement = $pdo->prepare($query); $statement->execute([ 'original_id' => $original_request_id, 'order_id' => $order_id, 'user_id' => $_SESSION['user_id'], 'product_id' => $products[$i], 'qty' => $qty[$i], ]); } //setup variables for system wide message function $send_to_users[] = ['user_id' => 54]; //r $send_to_users[] = ['user_id' => 49]; //b $send_to_users[] = ['user_id' => 55]; //g $send_to_users[] = ['user_id' => 1]; //j $message = 'An LED pull request has been made by: ' . get_user_full_name($_SESSION['user_id'], $pdo) . '. Please go to the LED Request Manager to review the request.'; //send the messages $chat_message_id = send_system_message( $message, $send_to_users, $order_id, $pdo ); //establish relationship for messages $pdo->query(' INSERT INTO chat_message_rel_leds( chat_message_id, original_request_id ) VALUES ( '. $chat_message_id .', '. $original_request_id .' ) '); } else { exit(); } }
Here is a screenshot of the problem:
If you look at row 235 and 236, they have a value of 233 and 234 in the 'original_request_id' column. If you look below 235, the last key was 232 so that should have been correct (original_request_id should be the initial key assigned to the record from the table). Is my method for determining what that key is going to be fault in some way? IE: $original_request_id = $pdo->query("SELECT MAX(id) FROM leds_requests LIMIT 1")->fetch(PDO::FETCH_NUM)[0] + 1; From what I understand, there isn't a way in PDO to get the current max primary key except after an insert function is performed. Is this correct and am I doing something wrong here? I am using function to insert into database. But the primary key is automatic and I used Quote $_SESSION['Tes_ID'] = mysql_insert_id(); to retrieve this. But now that I use function method. I am not sure how to retrieve the primary key on to the next page. Code: [Select] $value = modulesql($postVar1, $postVar2, $SessionVar1, $SessionVar2); $_SESSION['Tes_ID'] = mysql_insert_id(); echo $value, $_SESSION['Tes_ID']; Code: [Select] <?php function modulesql($Tes_Name, $Tes_Description, $Use_ID, $Sub_ID){ $con = OpenConnection(); mysql_select_db("examination", $con); $module = ("INSERT INTO test (`Tes_Name`, `Tes_Description`, `Use_ID`, `Sub_ID`) VALUES ($Tes_Name, $Tes_Description, $Use_ID, $Sub_ID)") or die('Cannot Execute:'. mysql_error()); CloseConnection($con); return $module; } ?> Have I lost you with my question?? Please i ran into this problem help me : Code: [Select] <p>Posted by <a href=""> <?php if(isset($_GET['id'])) { $tpid=$_GET['id']; } else { $tpid=$_POST['id']; } include"header.php"; $sql="SELECT*FROM topics WHERE topicsid='$tpid'"; $result=mysql_query($sql) or die(mysql_error()); while($row=mysql_fetch_array($result)) { echo"{$row['topics_by']}"; echo"</a></p>"; echo"<p>"; echo"{$row['topics_subject']}"; echo" <p align='left'><img src='speakout_1.png'/>"; echo"{$row['topics_content']}"; echo"<p class='post-footer align-right'> <a href='' class='comments'>"; session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo"Comments:".$_SESSION['views']; echo"</a>"; echo"<span class='date'>"; echo"{$row['topics_date']}"; } ?></span> </p> </div> <h3>Comments:</h3> <table> <tr class="row-a"> <td class="first"></td> <td><?php include"header.php"; $sql="SELECT post_content,post_by FROM post WHERE topicsID='$tpid'"; $result=mysql_query($sql)or die(mysql_error()); while($row=mysql_fetch_array($result)) { echo"<strong>{$row['post_by']}</strong>: {$row['post_content']}"."</br>"; } ?></td> </tr> </table> <?php include"header.php"; if(isset($_POST['submit'])) { $comment=mysql_real_escape_string(trim($_POST['comment'])); $name=mysql_real_escape_string(trim($_POST['name'])); $hidden=$_POST['id']; if($comment!=='' && $name!=='') { $ins="INSERT INTO post(topicsID,post_content,post_by)VALUES('$hidden','$comment','$name')"; mysql_query($ins) or die(mysql_error()); } else { echo"you cannot post an empty field"; } } ?> <h3>Post your comments here</h3> <form action=''method='post'> <textarea name="comment" id="content" style="width:400px;height:50px;background-color:#D0F18F;color:#000000;font:15px/20px cursive;scrollbar-base-color:#638E0D;"></textarea> <br /> Name:<input type="text"name="name"/> <input class="button" type="submit"name="submit"value="submit" /> <input type="hidden"name="id"value='<?php echo "$tpid"; ?>'/> </p> </form> <br /> </div> What exactly does the entry in the title mean? I cannot make sense out of it. I would appreciate if somebody can shed some light in. The error message occurs when I try to vote with the voting system I created. Hi, I am trying to build a function that takes in the current primary key as a parameter. My question is how do I extract it/retrieve it and store it in a variable? Any help is much appreciated! I have a successful select query, where I'm looping and building a row for getting parameters which works correctly while ($row = $orderDetailCheck->fetch(PDO::FETCH_ASSOC)) {
$params = [ } My issue now is that, for each row, I need to perform two merges because the data from that select is going to be split into two tables in db2. Some values are truly split between the tables but some values are shared between the two. I'm not sure the best way to perform these two merges because if the first one (products table) inserts, then it creates an ID that I need as a foreign key basically, to insert into the orders table. So on insert I need to grab that newly created ID and use it for ```product_id``` in the second merge. If the first merge performs the update when matched, then I need to grab the existing ID for that record so that I can update the proper record in the orders table. My two merge statements:
/*products table*/
:GROUP,
)
AS S(GROUP,DTL12,DTL13,CUSTNM,SELLINGN,COUNT_PLMN_1,LAST_DATE)
WHEN MATCHED
WHEN NOT MATCHED
/*ORDERS Table*/
/*need foreign key, which is id from products table*/
AS S(PRODUCT_ID,quantity_ordered,LAST_DATE,invoice_number)
WHEN MATCHED
WHEN NOT MATCHED Examples:
INVOICE | CUSTNM | SELLINGNUM | GROUP | DTL12 | DTL13 | QUANTITY | COUNT_PLMN_1 | LAST_DATE
products
ID | GROUP | DTL12 | DTL13 | CUSTNM | SELLINGNUM | COUNT_PLMN_1 | LAST_DATE
ORDERS
PRODUCT_ID | QUANTITY_ORDERED | LAST_DATE | INVOICE
INVOICE | CUSTNM | SELLINGNUM | GROUP | DTL12 | DTL13 | QUANTITY | COUNT_PLMN_1 | LAST_DATE
products
ID | GROUP | DTL12 | DTL13 | CUSTNM | SELLINGNUM | COUNT_PLMN_1 | LAST_DATE and update orders like so: ORDERS
PRODUCT_ID | QUANTITY_ORDERED | LAST_DATE | INVOICE I guess the main question is: How can I get the ID of a record from the products table (whether it's an existing match OR newly created in the merge) and once I get it, how can I use it for the 2nd merge? Hi there, I am trying to add a bit of php to capture an email address and add it to mysql database. This part works fine but i get this message: Error: Duplicate entry '' for key 'PRIMARY' How do i get rid of this error? Thanks! <?php session_start(); include('include/includes.php'); $cart = Cart::CreateInstance(); if(isset($_GET)){ foreach($_GET as $k=>$v){ $smarty->assign($k,$v); } } if(isset($_GET['remove'])){ $cart->RemoveItems($_GET['remove'],1); } if(isset($_GET['removeAll'])){ $cart->RemoveItems($_GET['removeAll'],$_GET['counts']); } if(isset($_GET['emptyCart'])){ if($_GET['emptyCart']){ $cart->EmptyCart(); header("Location: cart.html"); exit(0); }} if(isset($_GET['add'])){ $itemId = $_GET['add']; $size = $_GET['size']; if (isset($_GET['qty'])) { $qty = $_GET['qty']; } else { $qty = 1; } $cart->addItems($itemId.'-'.$size, array($size,$itemId), $qty); } $cart = Cart::CreateInstance(); $cartBox = $cart->GetCart(); //print_r($cartBox); $total = 0; $subTotal = array(); $db = new DB(); $prods = $db->select("SELECT friendly,name,id FROM products"); $smarty->assign('prods',$prods); if(is_array($cartBox)){ foreach($cartBox as $key=>$item){ $id = $cartBox[$key]['data']->_itemData[1]; $products = $db->select("SELECT detail,image,friendly,name FROM products WHERE id='$id'"); $detailjson = json_decode($products[0]['detail']); foreach($detailjson as $detail){ list($k, $v) = split_by_colon($detail); if($k == $cartBox[$key]['data']->_itemData[0]){ $price = $v;} } $cartBox[$key]['data']->_itemData[3] = $products[0]['image']; $cartBox[$key]['data']->_itemData[6] = $products[0]['name']; $cartBox[$key]['data']->_itemData[2] = $products[0]['friendly']; $cartBox[$key]['data']->_itemData[5] = $price; $sub = (int)$item['count'] * $price; $cartBox[$key]['data']->_itemData[4] = $sub; $total += $sub; } } else { $cartBox = array(); } $count = $cart->GetItemsCount(); $shipping = (int)0; if($total>0&&$total<5){ $shipping = 2.99; }elseif($total>5&&$total<10){ $shipping = 3.99; }elseif($total>10&&$total<15){ $shipping = 4.99; }elseif($total>15&&$total<20){ $shipping = 5.99; }elseif($total>20&&$total<30){ $shipping = 6.99; }elseif($total>30&&$total<40){ $shipping = 7.99; }elseif($total>40&&$total<50){ $shipping = 8.99; }elseif($total>50&&$total<60){ $shipping = 9.99; }elseif($total>60&&$total<70){ $shipping = 10.99; }elseif($total>70&&$total<80){ $shipping = 11.99; }elseif($total>80&&$total<90){ $shipping = 12.99; }elseif($total>90&&$total<100){ $shipping = 15.99; }elseif($total>100&&$total<110){ $shipping = 16.99; }elseif($total>110&&$total<120){ $shipping = 17.99; }elseif($total>120&&$total<130){ $shipping = 18.99; }elseif($total>130&&$total<140){ $shipping = 19.99; }elseif($total>140&&$total<150){ $shipping = 20.99; }elseif($total>150&&$total<160){ $shipping = 21.99; }elseif($total>160&&$total<170){ $shipping = 22.99; }elseif($total>170&&$total<180){ $shipping = 23.99; }elseif($total>180){ $shipping = 24.99; } /* 0 - 4.99 = 2.99 5 - 9.99 = 3.99 10 - 14.99 = 4.99 15 - 19.99 = 5.99 20 - 29.99 = 6.99 30 - 39.99 = 7.99 40 - 49.99 = 8.99 50 - 69.99 = 9.99 70 - 99.99 = 10.99 100+ = 12.99 */ if(isset($_GET['eushipping'])||(isset($_POST['rec_country'])&&$_POST['rec_country']!='uk')){ if($_POST['rec_country']=='au' || $_GET['country']=='au'){ //Set shipping for Austria $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='be' || $_GET['country']=='be'){ //Set shipping for Belgium $shipping = ceil($total/60.00)*20.00; }elseif($_POST['rec_country']=='bu' || $_GET['country']=='bu'){ //Set shipping for Bulgaria $shipping = ceil($total/60.00)*50.00; }elseif($_POST['rec_country']=='cy' || $_GET['country']=='cy'){ //Set shipping for Cyprus $shipping = ceil($total/60.00)*108.00; }elseif($_POST['rec_country']=='cz' || $_GET['country']=='cz'){ //Set shipping for Czech Republic $shipping = ceil($total/60.00)*33.00; }elseif($_POST['rec_country']=='de' || $_GET['country']=='de'){ //Set shipping for Denmark $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='es' || $_GET['country']=='es'){ //Set shipping for Estonia $shipping = ceil($total/60.00)*45.00; }elseif($_POST['rec_country']=='fi' || $_GET['country']=='fi'){ //Set shipping for Finalnd $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='fr' || $_GET['country']=='fr'){ //Set shipping for France $shipping = ceil($total/60.00)*28.00; }elseif($_POST['rec_country']=='ge' || $_GET['country']=='ge'){ //Set shipping for Germany $shipping = ceil($total/60.00)*25.00; }elseif($_POST['rec_country']=='gr' || $_GET['country']=='gr'){ //Set shipping for Greece $shipping = ceil($total/60.00)*50.00; }elseif($_POST['rec_country']=='hu' || $_GET['country']=='hu'){ //Set shipping for Hungary $shipping = ceil($total/60.00)*25.00; }elseif($_POST['rec_country']=='ir' || $_GET['country']=='ir'){ //Set shipping for Ireland $shipping = ceil($total/60.00)*25.00; }elseif($_POST['rec_country']=='it' || $_GET['country']=='it'){ //Set shipping for Italy $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='la' || $_GET['country']=='la'){ //Set shipping for Latvia $shipping = ceil($total/60.00)*42.00; }elseif($_POST['rec_country']=='li' || $_GET['country']=='li'){ //Set shipping for Lithuania $shipping = ceil($total/60.00)*35.00; }elseif($_POST['rec_country']=='lu' || $_GET['country']=='lu'){ //Set shipping for Luxembourg $shipping = ceil($total/60.00)*20.00; }elseif($_POST['rec_country']=='ma' || $_GET['country']=='ma'){ //Set shipping for Malta $shipping = ceil($total/60.00)*108.00; }elseif($_POST['rec_country']=='ne' || $_GET['country']=='ne'){ //Set shipping for Netherlands $shipping = ceil($total/60.00)*25.00; }elseif($_POST['rec_country']=='no' || $_GET['country']=='no'){ //Set shipping for Norway $shipping = ceil($total/60.00)*37.00; }elseif($_POST['rec_country']=='pol' || $_GET['country']=='pol'){ //Set shipping for Poland $shipping = ceil($total/60.00)*35.00; }elseif($_POST['rec_country']=='por' || $_GET['country']=='por'){ //Set shipping for Portugal $shipping = ceil($total/60.00)*30.00; }elseif($_POST['rec_country']=='ro' || $_GET['country']=='ro'){ //Set shipping for Romania $shipping = ceil($total/60.00)*48.00; }elseif($_POST['rec_country']=='slv' || $_GET['country']=='slv'){ //Set shipping for Slovakia $shipping = ceil($total/60.00)*32.00; }elseif($_POST['rec_country']=='slk' || $_GET['country']=='slk'){ //Set shipping for Slovenia $shipping = ceil($total/60.00)*29.00; }elseif($_POST['rec_country']=='sp' || $_GET['country']=='sp'){ //Set shipping for Spain $shipping = ceil($total/60.00)*36.00; }elseif($_POST['rec_country']=='swe' || $_GET['country']=='swe'){ //Set shipping for Sweden $shipping = ceil($total/60.00)*32.00; }elseif($_POST['rec_country']=='swi' || $_GET['country']=='swi'){ //Set shipping for Switzerland $shipping = ceil($total/60.00)*55.00; }elseif($_POST['rec_country']=='ukh' || $_GET['country']=='ukh'){ //Set shipping for UK - Highlnads and Islands $shipping = ceil($total/60.00)*18.00; }elseif($_POST['rec_country']=='ukn' || $_GET['country']=='ukn'){ //Set shipping for UK - Northern Island $shipping = ceil($total/60.00)*18.00; }elseif($_POST['rec_country']=='jng' || $_GET['country']=='jng'){ //Set shipping for Jersey and Guernsey $shipping = ceil($total/60.00)*34.00; } } /* */ if(isset($_GET['count'])){ echo (int)$count; exit; } if(isset($_GET['order'])){ if($_GET['order']){ }} if(isset($_GET['ajax'])){ $noAjax = $_GET['ajax']; }else{ $noAjax = false; } $smarty->assign('noAjax',$noAjax); if(isset($_GET['t'])){ $t=$_GET['t'].'.tpl'; } else { $t = 'cart.tpl'; } if(isset($_POST['cmd'])) { $_SESSION['paypal'] = $_POST; //print_r($_POST); } if(isset($_POST['rec_houseA1'])){ $filename = time().'-'.rand(1,499); $paypal = $_SESSION['paypal']; unset($paypal['checkout_x']); unset($paypal['checkout_y']); $_SESSION['addresses'] = $_POST; $File = 'sales/'.$filename.'.php'; $Handle = fopen($File, 'x'); fwrite($Handle,'<? '); fwrite($Handle,'$cart = array('); foreach($cartBox as $k=>$v){ fwrite($Handle,'"'.$k.'"=>array('); foreach($v as $key=>$value){ if(is_object($value)){ fwrite($Handle,'"'.$key.'"=>(object)array('); foreach($value as $keys=>$values){ if(is_array($values)){ fwrite($Handle,'"'.$keys.'"=>array('); foreach($values as $keyd=>$valued){ fwrite($Handle, '"'.$keyd.'"=>"'.$valued.'",'); } fwrite($Handle,'""=>""),'); }else{ fwrite($Handle, '"'.$keys.'"=>"'.$values.'",'); } } fwrite($Handle,'""=>""),'); }else{fwrite($Handle, '"'.$key.'"=>"'.$value.'",');} } fwrite($Handle,'""=>""),'); } //$total += $_POST['shipping']; fwrite($Handle,'"total"=>"'.$total.'");'); fwrite($Handle,' '); fwrite($Handle,'$detail = array('); foreach($_POST as $k=>$v){ if(is_array($v)){ fwrite($Handle,'array('); foreach($v as $key=>$value){ if(is_array($value)){ fwrite($Handle,'array('); foreach($value as $keys=>$values){ fwrite($Handle, '"'.$keys.'"=>"'.$values.'",'); } fwrite($Handle,')'); }else{fwrite($Handle, '"'.$key.'"=>"'.$value.'",');} } fwrite($Handle,')'); }else{ fwrite($Handle, '"'.$k.'"=>"'.$v.'",'); } } fwrite($Handle,'""=>"");'); fwrite($Handle,' '); fwrite($Handle,'$paypal = array('); foreach($paypal as $k=>$v){ if(is_array($v)){ fwrite($Handle,'array('); foreach($v as $key=>$value){ if(is_array($value)){ fwrite($Handle,'array('); foreach($value as $keys=>$values){ fwrite($Handle, '"'.$keys.'"=>"'.$values.'",'); } fwrite($Handle,')'); }else{fwrite($Handle, '"'.$key.'"=>"'.$value.'",');} } fwrite($Handle,')'); }else{ fwrite($Handle, '"'.$k.'"=>"'.$v.'",'); } } fwrite($Handle,'""=>"");'); fwrite($Handle,' '); fwrite($Handle,'$shipping = "'.$shipping.'"; '); fwrite($Handle,'$subtotal = "'.$total.'"; '); $totals = $total+$shipping; fwrite($Handle,'$totals = "'.$totals.'";'); fclose($Handle); $smarty->assign('filename',$filename); $smarty->assign('shipping',$shipping); $smarty->assign('paypal',$paypal); //print_r($paypal); $smarty->display('paypal.tpl'); }else{ $smarty->assign('total',$total+$shipping); $smarty->assign('itemsInBox',$count); $smarty->assign('cartBox',$cartBox); $smarty->assign('shipping',$shipping); $style = $db->select("SELECT * FROM styles WHERE `name`='default'"); $smarty->assign('style',$style); $smarty->display($t); } ?> <?php $con = mysql_connect("organicgrowshopcouk.fatcowmysql.com","worm","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ogs_mailinglist1", $con); $sql="INSERT INTO mailinglist (email) VALUES ('$_POST[rec_email]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); ?> I have a table with two columns. The first is an id column, set to be my primary key, non null, unique, int, and auto increment. The second is a varchar(10) column. Very strangely, when I set the varchar(10) column to unique, and try to edit the table in workbench, the table is automatically ordered by my varchar column, and not my id (primary key column). If I mark the varchar(10) column as not unique, data is ordered by the primary key, as expected. What is going on here? I expected the primary key to be default ordering for the table. I hope to not use an ORDER BY clause.
Edited by E_Leeder, 29 November 2014 - 02:14 AM. I am looking to use this functionality : http://www.w3schools...mob_collapsible
However using my own CSS style.
I looked at the source code, unfortunately the code is just jammed together so it isn't immediately clear how it works, I thought too that I could find every semi-colon and do a line escape but I don't know / think that javascript / jquery follows the same end of line statement as php.
I'm just looking to have a rectangle that when pushed, another rectangle of the same width but different color / font "extends" below this one, pushing the other elements below, away.
If anyone would care to chime in I'd appreciate it, otherwise I'll scrutinize the javascript/jquery code, I haven't worked with either too much yet.
Thanks
Edited by moose-en-a-gant, 17 January 2015 - 07:22 AM. I have a variable $form in the code below what I cant figure out how do it is call it and get the information it has out so I can display the errors: Code: [Select] function login($subuser, $subpass, $subremember){ global $database, $form; //The database and form object /* Username error checking */ $field = "user"; //Use field name for username if(!$subuser || strlen($subuser = trim($subuser)) == 0){ $form->setError($field, "* Username not entered"); } else{ /* Check if username is not alphanumeric */ if(!preg_match("^([0-9a-z])*$^i", $subuser)){ $form->setError($field, "* Username not alphanumeric"); } } if ($database->usernameBanned($subuser)) { $form->setError($field, "*Your Account has been banned"); } /* Password error checking */ $field = "pass"; //Use field name for password if(!$subpass){ $form->setError($field, "* Password not entered"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } /* Checks that username is in database and password is correct */ $subuser = stripslashes($subuser); $result = $database->confirmUserPass($subuser, md5($subpass)); /* Check error codes */ if($result == 1){ $field = "user"; $form->setError($field, "* Username not found"); } else if($result == 2){ $field = "pass"; $form->setError($field, "* Invalid password"); } /* Return if form errors exist */ if($form->num_errors > 0){ return false; } Hi, I am not very good with php but this code was kindly given to me by mdjamato, except I added a variable $markGradeSum to add all the $markGrade. Problem is that I will get notice saying undefined variable $markGradeSum because the $markGradeSum is in the foreach loop which it needs to be in for the right calculation but where I want to output the variable is in the while loop in this line: Code: [Select] $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong> <strong>Grade</strong> <br><strong>Year:</strong> {$row['Year'] $markGradeSum}</p>\n"; Below is whole code: Code: [Select] <?php if($num ==0){ echo "<p>Sorry, No Records were found from this Search</p>";} else{ function outputModule($moduleID, $moduleName, $sessionData) { if(!count($sessionData)) { return false; } $markTotal = 0; $markGrade = 0; $weightSession = 0; $markGradeSum = 0; $grade = ""; $sessionsHTML = ""; $courseHTML = ""; foreach($sessionData as $session) { $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} <strong>Session Mark:</strong> {$session['Mark']}</strong> <strong>Session Weight Contribution</strong> {$session['SessionWeight']}%</p>\n"; $markTotal += round($session['Mark'] / 100 * $session['SessionWeight']); $weightSession += ($session['SessionWeight']); $markGrade = round($markTotal / $weightSession * 100); $markGradeSum = round($markGrade); if ($markGrade >= 70){ $grade = "A";} else if ($markGrade >= 60 && $markGrade <= 69){ $grade = "B";} else if ($markGrade >= 50 && $markGrade <= 59){ $grade = "C";} else if ($markGrade >= 40 && $markGrade <= 49){ $grade = "D";} else if ($markGrade >= 30 && $markGrade <= 39){ $grade = "E";} else if ($markGrade >= 0 && $markGrade <= 29){ $grade = "F";} } $moduleHTML = "<p><br><strong>Module:</strong> {$moduleID} - {$moduleName} <strong>Module Mark:</strong> {$markTotal} <strong>Mark Percentage:</strong> {$markGrade} <strong>Grade:</strong> {$grade} </p>\n"; return $moduleHTML . $sessionsHTML; } $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong> <strong>Grade</strong> <br><strong>Year:</strong> {$row['Year'] $markGradeSum}</p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; } } ?> How can I retrieve the variable so it doesn't come up with the notice but be able to display $markGradeSum to the places I want them in (one in foreach loop for calculation and other in while loop for output). Thank You Hello, I have a booking system which has time and date fields and if someone tries to book, for example, on 01/01/2011 at 09:00, when this slot is already taken, an error would be produced - which is fine. However I'm not sure in telling them what hours are available. There are 9 available times: 09,10,11,12,13,14,15,16,17:00. I will need to perform an sql query to gather all the times on the inputted date, I'm guessing a for loop would be the most efficient way? The only way I could think of is using multiple IF queries, for example: Code: [Select] <?php $sql = "SELECT `Hour` FROM `jobs` WHERE `Hour` = '09:00:00' AND Day ='$Day' AND Month ='$Month' AND Year ='$Year'"; $result = mysql_query($sql); if(mysql_num_rows($result) > 0){ $09Available = 'n'; // Time not available }else{ $09Available = 'y'; } $sql = "SELECT `Hour` FROM `jobs` WHERE `Hour` = '10:00:00' AND Day ='$Day' AND Month ='$Month' AND Year ='$Year'"; $result = mysql_query($sql); if(mysql_num_rows($result) > 0){ $10Available = 'n'; // Time not available }else{ $10Available = 'y'; } $sql = "SELECT `Hour` FROM `jobs` WHERE `Hour` = '11:00:00' AND Day ='$Day' AND Month ='$Month' AND Year ='$Year'"; $result = mysql_query($sql); if(mysql_num_rows($result) > 0){ $11Available = 'n'; // Time not available }else{ $11Available = 'y'; } ?> etc. etc.. How would I go about creating a more efficient method? Thank you, Jack. Hi, Is it possible to retrieve all the information from a posted value without knowing the input field? My page is taking information from a database and then creates a page with checkboxs so that people can select certain fields. There are 1300 fields in the database so I don't know what fields will be submitted when a person saves the page, is there a simple way to check what fields have been submitted without writing a check for each checkbox? I hope this makes sense, thanks in advance for any help. I have a form where you can pick all the days in the week. When the form is posted my code finds the date of the day you picked that most recently went by. Then the code takes that date, and echos the date of every day of the week that you picked that comes after that date for a year. But for some reason he thinks we're in 2009, even though i know the date puts out that we're in 2010. Here's the code: <?php //function if(isset($_POST['submit'])) { function nextWeeksDay($date_begin,$nbrweek) { $nextweek=array(); for($i = 1; $i <= $nbrweek; $i++) { // 52 week in one year of course $nextweek[$i]=date('d-m-y', strtotime('+'.$i.' week',$date_begin)); } return $nextweek; } //Get what user posted as day, and find the date of the past day gone. $roday = $_POST['day']; echo $roday; echo date('d-m-y',strtotime('last ' . $roday)); $sistdag = date('d-m-y',strtotime('last ' . $roday)); /// end function /// example of a select date // var $date_begin = strtotime($sistdag); //D Day Month Year - like function format. $nbrweek=52; // call function $result=nextWeeksDay($date_begin,$nbrweek); // Preview for($i = 1; $i <= $nbrweek; $i++) { echo '<br> - '.$result[$i]; } } ?> All help appreciated! Hi, I want to be able to let user upload XML form, and then in the action page it needs to extract that so that I can add it to the database. Here is the upload form: Code: [Select] <html> <head></head> <body> <form method='post' action="uploadFileToDB.php" enctype="multipart/form-data"> <p> <label> Upload image<input type='file' name='imageFileType' id='imageFileType' /> </label> </p> <p> <input type='submit' value='Upload this image' name='upload' id='upload' /> </p> </form> </body> </html> Here is the uploadFileToDB.php: Code: [Select] <?php require("PHP_xml_parsing_via_DOM.php"); //NB: this script does the actual shreddering (XML to SQL) //IF User uploaded dir or XML file successful, then: if(isset($_POST['upload'])) { //SHRED NOW //NB: how to retrieve the uploaded xml file $_filePath=?? $node=basename($_filePath); $dom=new DOMDocument(); $dom->load($node); $labelPath=array(); mysql_connect("localhost","root"); mysql_select_db("dummydpev7"); $isXdocExist=mysql_query("SELECT file_Path,file_Name FROM xdocument WHERE file_Path='$_filePath' AND file_Name='$node'"); $docId=0; if(mysql_num_rows($isXdocExist)==1) { print "Entry already exists!"; $docId=mysql_next_id("xdocument")-1; } else { mysql_query("INSERT INTO xdocument (file_Path,file_Name) VALUES ('$_filePath','$node')"); $docId=mysql_next_id("xdocument")-1; } print "<br />".$docId; writeXMLtoDBViaDOM($dom->documentElement,$labelPath,$docId,$_filePath); } //ELSE else //Please upload Valid XML print "Problem with XML file being uploaded."; ?> The question in point is how do I extract the file I uploaded to set to $_filePath?? in the script so that I pass it to my function writeXMLtoDBviaDOM?? Please any help much appreciated! Submit2.php Code: [Select] <?php $db = mysql_connect("localhost", "root") or die("Could not connect."); //username and password if(!$db) die("no db"); if(!mysql_select_db("simple",$db)) if(!mysql_select_db("regis",$db))//database name die("No database selected."); $message=$_POST['message']; if(isset($_POST['submit'])) //if submit button push has been detected { $message=$_POST['message']; if(strlen($message)<1) { print "You did not input a message"; } else { $message=strip_tags($message); $IP=$_SERVER["REMOTE_ADDR"]; //grabs poster's IP $checkforbanned="SELECT IP from admin where IP='$IP'"; $checkforbanned2=mysql_query($checkforbanned) or die("Could not check for banned IPS"); if(mysql_num_rows($checkforbanned2)>0) //IP is in the banned list { print "You IP is banned from posting."; } else if(strlen($message)>=1) { $message=strip_tags($message); echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('$message')</SCRIPT>"); die("<meta http-equiv=\"refresh\" content=\"0; url=registration.php\">"); } $message=$_POST['message']; $message=strip_tags($message); /* if($_POST['username'] && $_POST['pass']) { $name = mysql_query("SELECT * FROM Persons"); $thedate = date("U"); //grab date and time of the post $insertmessage="INSERT into mesej (name,IP,postime,message) values('$name','$IP','$thedate','$message')"; mysql_query($insertmessage) or die("Could not insert message"); } */ } } if(!isset($message)) { print "<form action='' method='post' name='form'>"; print "Your message:<br>"; print "<textarea name='message' cols='40' rows='2'></textarea><br>"; print "<a onClick=\"addSmiley(':)')\"><img src='smile.gif'></a> "; print "<a onClick=\"addSmiley(':(')\"><img src='blush.gif'></a> "; print "<a onClick=\"addSmiley(';)')\"><img src='images/wink.gif'></a> "; print "<input type='submit' name='submit' value='Set Name'></form>"; print "<script language=\"Java Script\" type=\"text/javascript\">\n"; print "function addSmiley(a)\n"; print "{\n"; print "document.form.message.value += a;"; print "document.form.message.focus();\n"; print "}\n"; print "</script>\n"; print "<br><br>"; } ?> Registration.php Code: [Select] <?php $db = mysql_connect("localhost", "root") or die("Could not connect."); //username and password if(!$db){die("no db");} if(!mysql_select_db("regis",$db)){die("No database selected.");} $message=$_POST['message']; echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('$message')</SCRIPT>"); if (isset($_POST['sub'])) { $message=strip_tags($message); if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) { print "You did not complete all of the required fields"; } // checks if the username is in use if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM registration WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { print ('Sorry, the username '.$_POST['username'].' is already in use.'); } //this makes sure both passwords entered match if ($_POST['pass'] != $_POST['pass2']) { print ('Your passwords did not match. '); } // here we encrypt the password and add slashes if needed $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); } // now we insert it into the database if($_POST['username'] && $_POST['pass'] && $_POST['pass2'] ) { $insert = "INSERT INTO registration (username, password) VALUES ('".$_POST['username']."', '".$_POST['pass']."')"; $add_member = mysql_query($insert); echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('Registration had been succesfully added :)')</SCRIPT>"); print("<meta http-equiv=\"refresh\" content=\"0; url=login.php\">"); } } else { echo "<form action='registration.php' method='post'> <table border='0'> <tr><td>Username:</td><td> <input type='text'name='username' maxlength='60'> </td></tr> <tr><td>Password:</td><td> <input type='password' name='pass' maxlength='10'> </td></tr> <tr><td>Confirm Password:</td><td> <input type='password' name='pass2' maxlength='10'> </td></tr> <tr><th colspan=2><input type='submit' name='sub' value='Register'></th></tr> </table> </form> "; } im just want the message text area to be appear in registhration php in text box but its doest not appear instead the output is empty when im testing the first one that is : if(strlen($message)>=1) { $message=strip_tags($message); echo("<SCRIPT LANGUAGE='JavaScript'>window.alert('$message')</SCRIPT>"); die("<meta http-equiv=\"refresh\" content=\"0; url=registration.php\">"); that javascript box can run and read the same message that was input but when come to registrtaion php its only empty which way im wrong ? ?> Hello, I am trying to figure out how to grab the latest aim status update from "http://lifestream.aol.com/stream/iragedxt" But I can only see the Current Status if I am logged into my aim account on the website so is there a way I can log into my aim account on lifestream.aol.com and then I believe its to use curl to grab the text from the other website? if so could someone please help me with this? Thanks, John Dear All, I have login script already. i have two database one is users and another one is reference in both user_name is common. In this if a user login and search the refid means that user datas onle possible to retrieve. for others datas they cant access. i wrote the below code but it display all user datas. kindly help me <?php session_start(); if (!$_SESSION["user_name"]) { // User not logged in, redirect to login page Header("Location: login.php"); / } // Member only content // ... $con = mysql_connect('localhost','root',''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("login", $con); $user_name = $_POST['user_name']; $query = "select * from reference,users where reference.user_name=users.user_name and reference.refid='$refid'"; $result = mysql_query($query) or trigger_error('MySQL encountered a problem<br />Error: ' . mysql_error() . '<br />Query: ' . $query); while($row = mysql_fetch_array($result)) { echo $row['refid']; echo $row['origin']; echo $row['dest']; echo $row['date']; echo $row['exdate']; echo $row['user_name']; } echo "<p><a href=\"logout.php\">Click here to logout!</a></p>"; ?> <html> <form method="post" action="final.php"> Ref Id:<input type="text" name="refid"> <input type="submit" value="submit" name="submit"> </html> What php method is good for getting file from a .xml sheet ? |