PHP - How To Retrieve An Incremental Variable As Soon As It Is Inserted?
Hello,
Please could someone tell me how to retrieve an incremental variable from MYSQL as soon as it is inserted? (i.e. before another variable can be inserted) Many thanks. Stu Similar TutorialsI have two pages - add_product.php and show.php here is the code for add_product.php Code: [Select] <?php ini_set('display_errors',1); error_reporting(-1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Check for a name: if (empty($_POST['product'])) { $add_cat_errors['product'] = 'Please enter the name!'; } // Check for a description: if (empty($_POST['prod_descr'])) { $add_cat_errors['prod_descr'] = 'Please enter the description!'; } // Check for a category: if (!isset($_POST['cat']) || !filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['cat'] = 'Please select a category!'; } // Check for a price: if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) { $add_cat_errors['price'] = 'Please enter a valid price!'; } // Check for a category: if (!isset($_POST['directory']) || !filter_var($_POST['directory'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['directory'] = 'Please select a directory!'; } // Check for a stock: if (empty($_POST['stock']) || !filter_var($_POST['stock'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['stock'] = 'Please enter the quantity in stock!'; } if (empty($add_cat_errors)) { $query = "INSERT INTO product (product, prod_descr, catID, price, dirID, stock) VALUES (?, ?, ?, ?, ?, ?)"; // Prepare the statement: $stmt = mysqli_prepare($dbc, $query); // For debugging purposes: // if (!$stmt) echo mysqli_stmt_error($stmt); // Bind the variables: mysqli_stmt_bind_param($stmt, 'sssssi', $name, $desc, $_POST['cat'], $_POST['price'], $_POST['directory'], $_POST['stock']); // Make the extra variable associations: $name = strip_tags($_POST['product']); $desc = strip_tags($_POST['prod_descr']); // Execute the query: mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) == 1) { // If it ran OK. // Print a message: echo '<h4>The product has been added!</h4>'; // Clear $_POST: $_POST = array(); // Clear $_FILES: $_FILES = array(); } else { // If it did not run OK. trigger_error('The product could not be added due to a system error. We apologize for any inconvenience.'); } } // End of $errors IF. } else { // Clear out the session on a GET request: } // End of the submission IF. require_once ('./includes/form_functions.inc.php'); ?> <form enctype="multipart/form-data" action="add_image.php?prodID={$row['prodID']}" method="post" accept-charset="utf-8"> <input type="hidden" name="MAX_FILE_SIZE" value="524288" /> Product<br /><?php create_form_input('product', 'text', $add_cat_errors); ?> Description<br /><?php create_form_input('prod_descr', 'textarea', $add_cat_errors); ?> Category<br /><select name="cat"<?php if (array_key_exists('cat', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT catID, cat FROM category ORDER BY cat ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['cat']) && ($_POST['cat'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('cat', $add_cat_errors)) echo $add_cat_errors['cat']; ?> Price<br /><?php create_form_input('price', 'text', $add_cat_errors); ?> Directory<br /><select name="directory"<?php if (array_key_exists('directory', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT dirID, directory FROM directory ORDER BY directory ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['directory']) && ($_POST['directory'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('directory', $add_cat_errors)) echo $add_cat_errors['directory']; ?> </select> <br /> Stock<br /><?php create_form_input('stock', 'text', $add_cat_errors); ?> <input type="submit" value="Add This Product" class="button" /> </fieldset> </form> and here is the code for show.php Code: [Select] <?php ini_set('display_errors',1); error_reporting(-1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if($id = isset($_GET['prodID'])) { $q = "SELECT `prodID`, `product`, `prod_descr`, `catID`, `dirID`, `price`, `stock` FROM product WHERE `prodID`='{$_GET['prodID']}'"; $r = mysqli_query($dbc, $q); while($row = mysqli_fetch_array($r)) { echo $row['product']; echo "<br />"; echo $row['prod_descr']; echo "<br />"; echo $row['catID']; echo "<br />"; echo $row ['dirID']; echo "<br />"; echo $row['price']; echo "<br />"; echo $row['stock']; } } What I want is to try and retrieve the id of the last record inserted in add_product and pass it into show.php, but I get this error message. Quote An error occurred in script 'C:\Users\David Morgan\Desktop\WEBSITES\hairz_&_graces\site\admin\add_image.php' on line 16: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given I am struggling to find out where I am going wrong at the moment, if anyone could please help me that would be really appreciated. Am a newbie in php. Since I can't insert values to the database with respect to a user Id or with any other token using WHERE clause. I.e "INSERT INTO receipts(date) VALUES(example) where id="**....." If I need to fetch several values of column for a particular user, how do I go about it? Thank you!!! 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 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; } I am presuming that I set a global variable so that I can retrieve it on a different page...My filename is userid; and I will need this in many different pages. I set it thusly: Code: [Select] mysql_select_db($db , $link) or die("Couldn't open $db: ".mysql_error()); $long=$_SERVER['PHP_SELF']; //get path $text = substr(strrchr($long, "/"), 1); //get file name+extension $UserID = trim($text, " .php"); //remove extension, leaving userid Globals["UserID"]; and in a different file try to retrieve it thusly: echo "user is ".$GLOBALS["UserID"]; but all I ever see is "user is"------any help appreciated. I am trying to create a code where the user enters the zip code and if found in the database, a location will be retrieved. I am getting two undefined variables as errors. I am still learning the POST and GET method and I fear that is where I am getting something mixed up. I have also attached an image of my DB. Thank you so much any input is greatly appreciated. Notice: Undefined variable: address in C:\xampp\htdocs\index.php on line 53 Notice: Undefined variable: zip in C:\xampp\htdocs\index.php on line 54
<?php include ('header.php'); include ('function.php'); ?> <div class="wrapper"> <div> <?php echo'<form method="POST" action"'.getLocations($conn).'"> <input type="text" name="zip" class="search" placeholder="Zip code"><br> <button type="submit" value="submit" id="submit">Submit</button> </form>'; getLocations($conn); ?> </div> </div> <div> <!--foreach($zip as $zip) : --> <?php echo $address['address']; echo $zip['zip']; ?> </div> function.php file code: <?php $dBServername = "localhost"; $dBUsername = "root"; $dBPassword = ""; $dBName = "addresses"; // Create connection $conn = mysqli_connect($dBServername, $dBUsername, $dBPassword, $dBName); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } function getLocations($conn) { if (isset($_POST['submit'])){ // Validate Zip code field if (!empty ($_POST['zip']) && is_numeric ($_POST['zip'])) { $zip = (int)$_POST['zip']; $query = "SELECT * FROM locations WHERE zip = '$zip'"; //get the results $result = mysqli_query($conn, $query); //fetch the data $zip = mysqli_fetch_all($result, MYSQLI_ASSOC); var_dump($zip); mysqli_free_result($result); //close connection mysqli_close($conn); } } }
Hi, I want to be able to let user type in xml text and it will be parsed and uploaded to db, but it doesn't work, it just keeps redirecting me back to this form below! here is html form: Code: [Select] <html> <body> <form method='post' method='form.php'> <p> <textarea name="pastedXML" rows="10" cols="30"> Please paste your xml file here. </textarea> </p> <p> <input type="submit" value="Convert to SQL" name="textXML" /> </p> </form> </body> </html> Here is script (form.php;I just want to retrieve the contents typed in text area to store to variable...how??) Code: [Select] <?php //get the text in textarea and shred it! if(isset($_POST['textXML'])) print $_POST['pastedXML']; ?> Any help much appreciated! Have page#1 with thumbs view_thumbs.php , when a thumb is clicked thumb link goes to page#2 which is the video_play.php page(which must play embed codes from xml sheet) Using GET method to identify incoming link from page#1. QUESTION is how can i retrieve file(embed code) from xml to play on page#2 with incoming GET info from page#1? (embeds not you only from you tube, so no youtube solutions only, just retrieve file) I somehow have to fill play video div on page#2/video_play.php according to GET data from page#1/view_thumbs.php I have this interesting problem, I think I know how to do it.
In a java class I took there was a lab on swapping the values of variables and if there were two variables, you needed a third temporary value holder.
So this project I'm working on has a row output, currently the individual values are outputted as a concatenated string but ideally they would be independent rows with accompanying buttons.
One of those buttons is a ^ symbol, when you press this, ideally the row is moved up in ID putting the previous ID in front or ahead.
The problem is that the ID's / rows are not necessarily in sequential order.
So, when I recall a set of rows that have random sequential values for example, 2, 5, 27, 41, 43
and those are outputted by themselves, now becoming 0,1,2,3,4 respectively or 1,2,3,4,5
So when I try to move 43 to position 2, that's 4 positions away or 4 clicks of the ^ button.
Now how do you deal with that 4 difference and the difference of 41... ? thereby, when the initial set of rows are recalled again, the order is now, 43, 5, 27, 41, 2 Of course the ID I think remains the same but the data is switched... ? yeah I have to draw some pictures, but this isn't a current problem to fix, later on down the road after I update the interface.
here is a drawing to explain, I'm more of a visual person
wp_20150112_05_27_16_pro.jpg 59.67KB
0 downloads
Any ideas would be appreciated, otherwise I will post my solution when I come to it. Or I don't figure it out and find one.
thanks
I have an array of data in which I want to display in a table with the first row of data to not be formatted. In the second row of data, I want it formatted with the CSS class of "success". When I run this code, I do not get any formatting of any rows in the table. I have tried various different options without success. Any help would be greatly appreciated.
<?php Copied wrong set of code hi there, so okay i have a table named course which has 2 fields. c_id and c_name c_id here isn't unique but is indexed. okay,my problem is how to get the last inserted row in this table right after a record has been inserted. i was thinking i'd do a little query and then echo the results back to where the user fills up a form with c_id and c_name fields.. so is there a way to do this?like getting all values from the last inserted row? Wonder if someone can advise I have a script which runs on a CRON job, so every hour a script is activated. When the script runs, it INSERTS between 1 and 12 records into a database table, works a charm so far. When each QUERY is run on the script, it grabs the last ID number that was INSERTED and that is entered into another table, so if my script INSERTS a new row with an ID of 34877, then the ID number 34877 is entered into another database table. To grab the last ID number, I have always used $last_id = mysql_insert_id(); as seen on http://php.net/manual/en/function.mysql-insert-id.php which has always worked great. I now have to create another script on a CRON job, which does a similar TASK, it INSERTS a record into the same database and then grabs the last ID number. The plan is to roll about 150 of these script out, so each one is INSERTING data, and grabbing the last ID of the row just created. By 2015, they plan to have several thousand of these scripts, all being run at the same time. This is basically part of a bigger system and this is the method in which the 3rd party suppliers need data handled, so I have no option. My question is, if I have tons of scripts INSERTING data to the same database table and each time an INSERT is done, the last ID is grabbed, can PHP get overloaded and confused and then end up returning the wrong ID number of the row INSERTED. Or if I put $last_id = mysql_insert_id(); straight after each INSERT, then is it gurenteed that the right ID number is returned. Just concerned the QUERIES will end up in a que and incorrect ID numbers will be returned. Basically, is $last_id = mysql_insert_id(); flawless in getting the ID number of the row just INSERTED? Cheers everyone i have the following processing action for a form query DUMP output is: string(202) "INSERT INTO contactPO (Status, DateReceived, CustomerEmail, LastName, FirstName, PropertyID, fromdate, todate, nop) VALUES ('1', '24-08-2011', 'r', 'r', 'rrrrr', '12121', '27-10-2011', '30-10-2011','4')" but nothing is inserted Code: [Select] <?php $con = mysql_connect("localhost","international",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_query("SET NAMES 'utf8'"); mysql_select_db("international", $con); // check which button was clicked // perform calculation if ($_POST['send']) { $query = sprintf("INSERT INTO contactPO (Status, DateReceived, CustomerEmail, LastName, FirstName, PropertyID, fromdate, todate, nop) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s')", mysql_real_escape_string($_POST['Status']), mysql_real_escape_string($_POST['DateReceived']), mysql_real_escape_string($_POST['CustomerEmail']), mysql_real_escape_string($_POST['LastName']), mysql_real_escape_string($_POST['FirstName']), mysql_real_escape_string($_POST['PropertyID']), mysql_real_escape_string($_POST['fromdate']), mysql_real_escape_string($_POST['todate']), mysql_real_escape_string($_POST['nop'])); var_dump($query ); //$url_success = "search-index.php?RID=".$_POST['RequestID'].""; $url_success = "search-index.php"; echo("<meta http-equiv = refresh content=6;url=".$url_success.">"); exit; mysql_close($con); } ?> Hi, I am making a website where the user can create a login and he's then redirected to the secured pages this is working ok. Then I want the user who's not yet completely registered to enter his full name and credentials and store this data in the table Owner. however when I am trying to do this with the below mentioned code I don't get any output on error level and I don't get any data inserted in my table what am I missing here Code: [Select] <?php //session starten session_start(); ini_set('display_errors', 'On'); error_reporting(E_ALL | E_STRICT); print_r($_SESSION['user_id']); //database verbinding maken mysql_connect("127.0.0.1", "root", "pass")or die("cannot connect"); mysql_select_db("tobysplace")or die("cannot select DB"); //kijken of de gebruikers_id al gekend is in de tabel Owner $result = mysql_query("Select gebruiker_id from Owner where gebruiker_id ='".mysql_real_escape_string($_SESSION['user_id'])"'"); If(!$result){ $gebruiker_id = mysql_insert_id(); } else { $gebruiker_id = mysql_real_escape_string($_SESSION['user_id']); } //de gegevens van de eigenaar wegschrijven in de database $Owner_query="insert into Owner( name, lastname, email, address1, town, postcode, phone, gebruiker_id)values( '" . mysql_real_escape_string($_SESSION['name']) . "', '" . mysql_real_escape_string($_SESSION['lastname']) . "', '" . mysql_real_escape_string($_SESSION['email']) . "', '" . mysql_real_escape_string($_SESSION['address1']) . "', '" . mysql_real_escape_string($_SESSION['town']) . "', '" . mysql_real_escape_string($_SESSION['postcode']) . "', '" . mysql_real_escape_string($_SESSION['phone']) . "', '" . mysql_real_escape_string($_SESSION['user_id']) ."')"; // // de query uitvoeren $result=mysql_query($Owner_query) //foutcontrole or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $Owner_query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error()); print '<p>'.$_SESSION['name'].' U bent met succes ingeschreven op tobys-place</p>'; //} ?> Basically the following code works fine, exepct when it comes to the last result it inserts it twice, example: (3,17),(4,17),(5,17),(5,17) Any clues as to why? Thanks Code: [Select] if(count($addIDs_ary) > 0) { $str = ""; foreach($addIDs_ary as $val) { $str .= "({$val},{$playerID}),"; if(end($addIDs_ary) == $val) { $str .= "({$val},{$playerID})"; } } echo $str; // (val,val), (val,val), (val,val) etc.. $query = "INSERT INTO hitlist (hit_id,player_id) values $str"; If the user signs up and does not have an avatar, a default will be given to them. I am checking for the avatar/image file, however, that is not working. Here is the messy code below: if ($_SERVER['REQUEST_METHOD'] == 'POST') { // $username = $_POST['username']; // adds user info submitted upon registration to database function addUser($pdo) { $username = $_POST['username']; $password = password_hash($_POST['password'], PASSWORD_DEFAULT); $bio = $_POST['bio']; $email = $_POST['email']; $c_status = 0; $query = $pdo->prepare("INSERT into profiles001 (username, password, email, c_status, bio) VALUES (:username, :password, :email, :cstat, :bio)"); $query->bindValue(':username', $username); $query->bindValue(':password', $password); $query->bindValue(':email', $email); $query->bindValue(':cstat', $c_status); $query->bindValue(':bio', $bio); $file = $_FILES['userfile']; $file_name = $file['name']; $file_type = $file['type']; $file_size = $file['size']; $file_tmp_name = $file['tmp_name']; $file_error = $file['error']; if (!isset($_FILES['userfile'])) { $avatar = "assets/soap.jpg"; $avatar_present_query = $pdo->prepare("INSERT into profiles001 (avatar) VALUES (:avatar) WHERE username = ':username'"); $avatar_present_query->bindValue(':avatar', $avatar); $avatar_present_query->bindValue(':username', $username); $avatar_present_query->execute(); $query->execute(); } // $query->execute(); } addUser($pdo);
I have a small form, then after submit it inserts a new row with a few values (time, email) This form also sends email to the email from the form with a link. Problem, the link needs to contain an autoincrement value from the newly inserted row. How can I do this? (the form that obvioulsy doesn't work, for obviously reasons but to show what I try to accomplish:P) Code: [Select] <? if (isset($_REQUEST['Submit'])) { $time= time(); # THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE $sql = "INSERT INTO phpfox_invite (user_id,email,time_stamp,is_used) values ('".$b."','".mysql_real_escape_string(stripslashes($_REQUEST['email']))."','".$time."','1')"; $sql = mysql_query("SELECT invite_id FROM phpfox_invite WHERE email='".mysql_real_escape_string(stripslashes($_REQUEST['email']))."'"); $result = mysql_fetch_array( $sql ); $inviteid = $result['invite_id']; if($result = mysql_query($sql)) { $modtager = "".mysql_real_escape_string(stripslashes($_REQUEST['email'])).""; $emne = "Please complete Your registration"; $besked = "Click the link below to complete your registration: \n http://domain.com/invite/id_".$inviteid." "; $header = "from:system@domain.com"; mail($modtager, $emne, $besked, $header); echo 'Check Your Email!'; } else { echo "ERROR: ".mysql_error(); } ?> Everything works ok, but ofcourse I cannot get the 'invite_id' before the form is submitted and therefor cannot send the value im trying to insert a value in to mysql using an experiment everything works fine after hitting the insert button but the problem arises wen i refresh the page as a empty value gets inserted in to the mysql table wen i refresh it.(pardon my english)
this is the index page where i fetch an result from mysql table:
<div id="container"> <div class="Container-left"> </div> <div class="container-right"> <form action="1.2.php" method="post"> <textarea height="190px" width="190px" name="text" placeholder="share wats on your mind"></textarea> <br> <input type="submit" name="button" value="Type Here" /> </form> <hr> <?php include '1.2.php'; while ($fetch = mysqli_fetch_array($query1)) { echo 'comment:'.$fetch['post'].'<br/>'; echo '<small>date:'.$fetch['date'].'</small><br/><hr>'; } ?> </div> </div>this is the page where my second code rests: <?php include 'config.php'; error_reporting(E_ALL ^ E_NOTICE); $h= htmlspecialchars($_POST['text']); $p= mysqli_real_escape_string($conn,$h); $sql = "INSERT INTO article (post) VALUES ('$h') "; $sql1="SELECT * FROM article"; $query=mysqli_query($conn, $sql); $query1= mysqli_query($conn, $sql1); if ($_POST['button']){ echo 'inserted'; } else { echo 'not inserted'. mysqli_error($conn); }what should i do to stop value getting inserted in to my table while refreshing the page. pl help and thanks in advance. Edited by shan, 06 January 2015 - 09:18 AM. im playing around with a rating star jquery, i trying to get the value from the radio group but it is not selected??? Code: [Select] <?php require_once('Connections/international.php'); ?> <? mysql_query("SET NAMES 'utf8'")?> <!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>jQuery Star Rating Plugin v3.13 (2009-03-26)</title> <script src='http://jquery-star-rating-plugin.googlecode.com/svn/trunk/jquery.js' type="text/javascript"></script> <script src='http://jquery-star-rating-plugin.googlecode.com/svn/trunk/documentation.js' type="text/javascript"></script> <link href='http://jquery-star-rating-plugin.googlecode.com/svn/trunk/documentation.css' type="text/css" rel="stylesheet"/> <script type="text/javaScript" src="http://www.fyneworks.com/jquery/project/chili/jquery.chili-2.0.js"></script> <script type="text/javascript">try{ChiliBook.recipeFolder="/jquery/project/chili/"}catch(e){}</script> <script src='http://jquery-star-rating-plugin.googlecode.com/svn/trunk/jquery.MetaData.js' type="text/javascript" language="javascript"></script> <script src='http://jquery-star-rating-plugin.googlecode.com/svn/trunk/jquery.rating.js' type="text/javascript" language="javascript"></script> <link href='http://jquery-star-rating-plugin.googlecode.com/svn/trunk/jquery.rating.css' type="text/css" rel="stylesheet"/> </head> <body> <a name="top"></a> <div id="wrap"> <div id="body"> <div id="documentation" class="tabs"> <div id="tab-Testing"> <h2>Test Suite</h2> <script type="text/javascript" language="javascript"> $(function(){ $('#form1 :radio.star').rating(); $('#form2 :radio.star').rating({cancel: 'Cancel', cancelValue: '0'}); $('#form3 :radio.star').rating(); $('#form4 :radio.star').rating(); }); </script> <script> $(function(){ $('#tab-Testing form').submit(function(){ $('.test',this).html(''); $('input',this).each(function(){ if(this.checked) $('.test',this.form).append(''+this.name+': '+this.value+'<br/>'); }); return false; }); }); </script><div class="Clear"> </div> <form name="form1" id="form1" method="POST"> <strong style='font-size:150%'>Test 2</strong> - With defaults ('checked') <table width="100%" cellspacing="10"> <tr> <td valign="top" width=""> <table width="100%"> <tr> <td valign="top" width="50%"> <div class="Clear"> Rating 1: (N/M/Y, default M) </div> <div class="Clear"> <input class="star" type="radio" name="rating1" value="0" id="rating1_0" title="0"/> <input class="star" type="radio" name="rating1" value="1" id="rating1_1" title="1"/> <input class="star" type="radio" name="rating1" value="2" id="rating1_2" title="2"/> </div> <div class="Clear"> Rating 2: (10 - 50, default 30) </div> <div class="Clear"> <input class="star" type="radio" name="rating22" value="10"/> <input class="star" type="radio" name="rating22" value="20"/> <input class="star" type="radio" name="rating22" value="30" checked="checked"/> <input class="star" type="radio" name="rating22" value="40"/> <input class="star" type="radio" name="rating22" value="50"/> </div> <div class="Clear"> Rating 3: (1 - 7, default 4) </div> <div class="Clear"> <input class="star" type="radio" name="rating23" value="1"/> <input class="star" type="radio" name="rating23" value="2"/> <input class="star" type="radio" name="rating23" value="3"/> <input class="star" type="radio" name="rating23" value="4" checked="checked"/> <input class="star" type="radio" name="rating23" value="5"/> <input class="star" type="radio" name="rating23" value="6"/> <input class="star" type="radio" name="rating23" value="7"/> </div> </td> <td valign="top" width="50%"> <div class="Clear"> Rating 4: (1 - 5, default 1) </div> <div class="Clear"> <input class="star" type="radio" name="rating24" value="1" title="Worst" checked="checked"/> <input class="star" type="radio" name="rating24" value="2" title="Bad"/> <input class="star" type="radio" name="rating24" value="3" title="OK"/> <input class="star" type="radio" name="rating24" value="4" title="Good"/> <input class="star" type="radio" name="rating24" value="5" title="Best"/> </div> <div class="Clear"> Rating 5: (1 - 5, default 5) </div> <div class="Clear"> <input class="star" type="radio" name="rating25" value="1"/> <input class="star" type="radio" name="rating25" value="2"/> <input class="star" type="radio" name="rating25" value="3"/> <input class="star" type="radio" name="rating25" value="4"/> <input class="star" type="radio" name="rating25" value="5" checked="checked"/> </div> <div class="Clear"> Rating 6 (readonly): (1 - 5, default 3) </div> <div class="Clear"> <input class="star" type="radio" name="rating26" value="1" disabled="disabled"/> <input class="star" type="radio" name="rating26" value="2" disabled="disabled"/> <input class="star" type="radio" name="rating26" value="3" disabled="disabled" checked="checked"/> <input class="star" type="radio" name="rating26" value="4" disabled="disabled"/> <input class="star" type="radio" name="rating26" value="5" disabled="disabled"/> </div> </td> </tr> </table> </td> <td valign="top" width="5"> </td> <td valign="top" width="50"> <input type="submit" value="Submit" name="submit"/> </td> <td valign="top" width="5"> </td> <td valign="top" width="160"> <u>Test results</u>:<br/><br/> <div class="test Smaller"> <span style="color:#FF0000">Results will be displayed here</span> </div> </td> </tr> </table> <script> $(function(){ $('.hover-star').rating({ focus: function(value, link){ // 'this' is the hidden form element holding the current value // 'value' is the value selected // 'element' points to the link element that received the click. var tip = $('#hover-test'); tip[0].data = tip[0].data || tip.html(); tip.html(link.title || 'value: '+value); }, blur: function(value, link){ var tip = $('#hover-test'); $('#hover-test').html(tip[0].data || ''); } }); }); </script> <div class="Clear"> </div><div class="Clear"> </div> </div> </div> </div> <div id="push"></div> </div> </form> </body></html> <?php mysql_select_db($database_international, $international); $query=mysql_query("INSERT INTO ratings_tbl (Comfort) VALUES ('$_POST[rating1]'')"); $selected_radio = $_POST['rating1']; echo $selected_radio; var_dump($_POST); ;?> Hello all! I'm having a problem inserting an array into my database. My database is connected when I run the script but my table isn't being populated. Please help! Here's my table structure followed by the php: CREATE TABLE `demographic` ( `uid` bigint(20) unsigned NOT NULL, `first_name` varchar(50) default NULL, `last_name` varchar(50) default NULL, `email` varchar(200) default NULL, `link` varchar(255) default NULL, `affiliations` varchar(255) default NULL, `birthday` varchar(50) default NULL, `current_location` varchar(200) default NULL, `education_history` varchar(500) default NULL, `work` mediumtext, `hometown_location` varchar(400) default NULL, `interests` varchar(200) default NULL, `locale` varchar(50) default NULL, `movies` varchar(500) default NULL, `music` varchar(500) default NULL, `political` varchar(200) default NULL, `relationship_status` varchar(100) default NULL, `sex` varchar(10) default NULL, `tv` varchar(200) default NULL, `status` tinyint(4) default NULL, `created` datetime default NULL, `updated` datetime default NULL, PRIMARY KEY (`uid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; <?php $link = mysql_connect('host', 'user', 'pass'); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db('database'); if (!$db_selected) { die ('Can\'t use beta : ' . mysql_error()); } echo 'Connected successfully'; mysql_close($link); include_once "fbmain.php"; $config['baseurl'] = "baseurl"; //if user is logged in and session is valid. if ($fbme){ //collect some data using legacy api $param = array( 'method' => 'users.getinfo', 'uids' => $fbme['id'], 'fields' => 'birthday_date, interests, locale, political, relationship_status, affiliations', 'callback' => '' ); try{ $info = $facebook->api($param); } catch(Exception $o){ error_log("Legacy Api Calling Error!"); } //using graph api //array data $workInfo = getWorkInfoAsString($fbme); $education = getEducationAsString($fbme); $moviesArr = $facebook->api("/me/movies"); $musicArr = $facebook->api("/me/music"); $televisionArr = $facebook->api("/me/television"); //format some api data $movies = getArrayDataAsString($moviesArr['data']); $music = getArrayDataAsString($musicArr['data']); $television = getArrayDataAsString($televisionArr['data']); //data from legacy api $networks = ''; if (!empty($info[0]['affiliations'])){ $flag = true; foreach ($info[0]['affiliations'] as $item){ if (!$flag) $networks.= ' # '; $networks .= $item['name']; $flag = false; } } $now = date("Y-m-d G:i:s"); $insData = array( 'uid' => $fbme['id'], 'first_name' => $fbme['first_name'], 'last_name' => $fbme['last_name'], 'email' => isset($fbme['email']) ? $fbme['email'] : '', 'link' => $fbme['link'], 'affiliations' => $networks, 'birthday' => $info[0]['birthday_date'], 'current_location' => isset($fbme['location']['name']) ? $fbme['location']['name'] : '', 'education_history' => $education, 'work' => $workInfo, 'hometown_location' => isset($fbme['hometown']['name']) ? $fbme['hometown']['name'] : '', 'interests' => $info[0]['interests'], 'locale' => $info[0]['locale'], 'movies' => $movies, 'music' => $music, 'political' => $info[0]['political'], 'relationship_status' => $info[0]['relationship_status'], 'sex' => isset($fbme['gender']) ? $fbme['gender'] : '', 'tv' => $television, 'status' => '0', 'created' => $now, 'updated' => $now, ); $this->db->insert('demographic', $insData); } function getWorkInfoAsString($fbme, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; if (empty($fbme['work'])) return ''; foreach($fbme['work'] as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= (isset($item['employer']['name']) ? $item['employer']['name'] : '' ). $delim . (isset($item['location']['name']) ? $item['location']['name'] : '' ). $delim . (isset($item['position']) ? $item['position']['name'] : '' ). $delim . (isset($item['start_date']) ? $item['start_date'] : '' ). $delim . (isset($item['end_date']) ? $item['end_date'] : '' ); } return $info; } function getEducationAsString($fbme, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; if (empty($fbme['education'])) return ''; foreach($fbme['education'] as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= (isset($item['school']['name']) ? $item['school']['name'] : '' ). $delim . (isset($item['year']['name']) ? $item['year']['name'] : ''); } return $info; } function getArrayDataAsString($data, $delim = '#', $partDelim = ' | '){ $info = ""; $flag = false; foreach($data as $item){ if ($flag) $info .= $partDelim; $flag = true; $info .= $item['name']; } return $info; } ?> |