PHP - Getting Mysql_insert_id() From Multiple Inserts
If I am running a query like this:
INSERT INTO `cam_locations` (`id`, `datacenter`, `address1`, `address2`, `city`, `state`, `zip`, `country`, `phone`) VALUES (1, 'Austin Data Center', '', '', 'Austin', 'Texas', '', 'United States', ''), (2, 'Sunnyvale Date Center', '', '', 'Sunnvale', 'California', '', 'United States', ''), (4, 'BoxBorough Data Center', '', '', 'Boston', 'Massachusetts', '', 'United States', '') It it possible to use mysql_insert_id() and get all the id's inserted? Maybe like an array of them or something? Thanks Similar TutorialsHi all. Im trying to insert from one form 3 items of data into to different tables. I will post the code as most of my notes are in there but first....... What is happening is the form is filled in then the first part of the form where it updates my clubs table with category ID's works fine. Nothing in the if ($result) { } seems to run. I have create some fake groups so the drop down is populated with groups already created and I have tried to select one of these groups so it can be entered into the clubs table and nothing. No errors just no answers. Does anybody no what I am doing wrong? first Ill post the form and the querys that make fields in the form... Querys //gets $validation = $_GET['new_club']; //Querys $qGetClub = "SELECT * FROM clubs WHERE validationID = '$validation'"; $rGetClub = mysql_query($qGetClub); $Club = mysql_fetch_array($rGetClub); //Query for category by name $qGetCat = "SELECT * FROM club_category WHERE catID = ".$Club['cat'].""; $rGetCat = mysql_query($qGetCat); $CatName = mysql_fetch_array($rGetCat); //query for related sub categorys. $qGetSub = "SELECT * FROM sub_categorys WHERE catID =".$Club['cat'].""; $rSubCat = mysql_query($qGetSub); // query for groups created $Groupq = mysql_query("SELECT * FROM groups WHERE memberID = '".$User['memberID']."'"); then we have the form <form action="" method="post" id="insert_clubfrm"> <tr valign="baseline"> <td colspan="2" valign="top"><br/><p>Your Chosen category was <strong><?php echo $CatName['categorys'];?></strong> Please select a sub category.</p><br></td> </tr> <tr valign="baseline"> <td width="132" valign="top" >Club Sub Category:</td> <td width="256" valign="top" ><select name='subcat'> <option value="None">Please Select One</option> <?php while ($New_SubCat = mysql_fetch_assoc($rSubCat)) { ?> <option value="<?php echo $New_SubCat['subID']; ?>"><?php echo $New_SubCat['sub_categorys']; ?></option>"<?php } ?> </select> </td> </tr> <tr valign="baseline"> <td colspan="2" valign="top" ><br/><p>If your sub category does not exist in the list please select "none" above and enter your new sub categroy below.</p><br></td> </tr> <tr valign="baseline"> <td valign="top" class="left_padding">New Sub Category</td> <td valign="top" class="left_padding"><input type="text" name="newSubCat" id="new_cat" value="" /></td> </tr> <tr valign="baseline"> <td colspan="2" valign="top" class="left_padding"><br/> If you had/have more than one site and you had to give your group of companies a name what would that name be? <br/></td> </tr> <tr valign="baseline"> <td valign="top" class="left_padding">Group Name:</td> <td valign="top" class="left_padding"><label for="other_groups"></label> <select name="other_groups" id="other_groups"> <option>None</option> <?php while ($group = mysql_fetch_assoc($Groupq)) { ?> <option value="<?php echo $group['groupID']; ?>"><?php echo $group['group']; ?></option>"<?php } ?> </select></td> </tr> <tr valign="baseline"> <td valign="top" class="left_padding">Group Name:</td> <td valign="top" class="left_padding"><label for="new_groups"></label> <input type="text" name="new_group" value=""> </td> </tr> <tr valign="baseline"> <td valign="top" nowrap="nowrap"> </td> <td valign="top"><div align="left"> <input type="submit" id="insert_clubbtn1" name="insert_clubbtn1" value="Insert record" /> </div></td> </tr> </table> </form> now the code to make the form work... if(isset($_POST['insert_clubbtn1'])){ //Process data for validation $subcat = trim($_POST['subcat']); $NewSubCat = trim($_POST['NewSubCat']); $otherg = trim($_POST['other_groups']); $newg = trim($_POST['new_groups']); //Prepare data for db insertion $newg = mysql_real_escape_string($newg); $subcat = mysql_real_escape_string($subcat); //find the new category //insert $result = mysql_query("UPDATE clubs SET `sub_category` = '$subcat' WHERE validationID ='$validation'") or die(mysql_error()); if ($result) { //if an item other than none from the list is selected then update the club with an ID relating to the group it belongs to if ($otherg !=='None') { $groupsq = mysql_query("UPDATE `clubs` SET groupID ='$otherg' WHERE validationID ='$validation')") or die (mysql_error()); } // If none is selected then $newg must have a value so create a new group in the groups table and then on the next page I will add the group in the club table if ($otherg == 'None') { $groupsq = mysql_query("INSERT INTO `groups` (memberID, group, clubID) VALUES ('".$User['memberID']."', '$newg', ''".$Club['clubID']."')"); } } if ($NewSubCat !="") { mail("email","New Sub Category Request","Dear Owner, \n\nThe club in the name of $name with a validation code of $validationID would like a new sub category called $new_cat\n\n \nTeam Me\n\n\n\n"); } $url = "/create/create_clubp3.php?new_club=$validation"; header("Location: $url"); Hi Everyone, I have a code that stores an ID to a cookie named "cookieuser" and inserts it to a table named "cookieuser" wheneven someone new to my site visited. When someone revisits, it should only access the cookie in the computer and retrieve data in the table based on the cookie. The problem is, the code inserts multiple rows with different IDs (which is autoincremented). The codes works for returning visitors which only reads the cookie ID value. I noticed that the error reacts differently with different browsers: When in localhost, mozilla works as expected, ie inserts 4 rows, and chrome inserts 2 rows. In live server, mozilla creates 4 rows as well. The code I used is shown below. Hope someone knows the problem. Thank you in advance. Code: [Select] if (isset($_COOKIE['cookieuser'])) { $cookieuserx = $_COOKIE['cookieuser']; $sql = "SELECT userid FROM cookieuser WHERE userid = $cookieuserx"; $res = mysql_query($sql) or die(mysql_error()); if(mysql_num_rows($res) == 0){ $date = date("Y-m-d H:i:s",time()); $sqlcookie = "INSERT INTO cookieuser (userid,lastgood,lastbad,lastneutral,lastvisit,hitcount,date_registered) VALUES('','$date','$date','$date','$date','1','$date')"; $rescookie = mysql_query($sqlcookie) or die(mysql_error()); $newcookieuser = mysql_insert_id(); $expire=time()+60*60*24*360; setcookie("cookieuser", $newcookieuser, $expire,"/"); $cookieuser = $newcookieuser; }else{ $cookieuser = $_COOKIE['cookieuser']; } }else{ $date = date("Y-m-d H:i:s",time()); $sqlcookie = "INSERT INTO cookieuser (userid,lastgood,lastbad,lastneutral,lastvisit,hitcount,date_registered) VALUES('','$date','$date','$date','$date','1','$date')"; $rescookie = mysql_query($sqlcookie) or die(mysql_error()); $newcookieuser = mysql_insert_id(); $expire=time()+60*60*24*360; setcookie("cookieuser", $newcookieuser, $expire,"/"); $cookieuser = $newcookieuser; } how do i stop multiple duplications in database on my PHP script? ok i have attached a screenshot of what the database looks like after a few runs of my script. the script is designed to pull api information, input into 1 database and update another user table. i have made it run as a cron job every 60 minutes. here is my code: <?php /* You need multiple instances of this script. Each instance runs once every hour so 6 instances means one runs every 10 mins. Remember to change the API URL to reflect the different accounts or characters.*/ include "connect.php"; $columns = "`date` , `refID`, `refType`, `ownerName1`, `ownerName2`, `argName1`, `amount`, `balance`, `reason`"; //Live URL is //Assumeing that they are only donating at this time and no one is being paid to reduce the balance. Balance reduction can be done in the prize claim script so its not API delayed. if ( ($data[2] == "Player Donation") && ($data[4] == "Ship Lotto")){ $reUsed = mysql_query("SELECT * FROM bank WHERE refID='$data[1]';"); if(!empty($reUsed)){ $import="INSERT into bank($columns) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')"; mysql_query($import) or die(mysql_error()); } /*check to see if the player has already been credited. It checks the last recorded reference # and checks to see if the new ref # is greater, else skips the processing. You need to check since the API gives you the last 1000 journal entries or 1 week, what ever is shorter. Not just what is new since last check. Check is performed by seeing if the record in the database for the user is less then or equal to the new once. This works only because CCP's reference #s are auto increasing so they only go up if they are newer, never down.*/ $name = $data[3]; //echo "Updating account of ".$name."<br />"; $queryLastRef = mysql_query("SELECT lastRef FROM users WHERE username='$name';") or die(mysql_error()); //echo $queryLastRef; $arraylastRef = mysql_fetch_assoc($queryLastRef); $lastRef = $arraylastRef["lastRef"]; //echo "The last reference # was: ".$lastRef."<br />"; $currentRef = $data[1]; //echo "The current reference # is: ".$currentRef."<br />"; if($lastRef<$currentRef){ $amount = $data[6]; //echo "Player deposited ISK in the amount of: ".$amount."<br />"; $queryBal = mysql_query("SELECT user_iskbalance FROM users WHERE username='$name';") or die(mysql_error()); //echo "Executing the SQL command to query balance ID#: ".$queryBal."<br />"; $getBal = mysql_fetch_assoc($queryBal); //echo "Executing the SQL command to get balance amount: ".$getBal["user_iskbalance"]."<br />"; $deposit = $amount+$getBal["user_iskbalance"]; //echo "Depositing ISK in the ammount of: ".$deposit."<br />"; $importBal= "UPDATE users SET user_iskbalance=$deposit WHERE username='$name';"; //echo "Executing the SQL command to desposit: ".$importBal."<br />"; mysql_query($importBal) or die(mysql_error()); $importRefID= "UPDATE users SET lastRef='$currentRef' WHERE username='$name';"; //echo "Executing the SQL command to set the new reference: ".$currentRef."<br />"; mysql_query($importRefID) or die(mysql_error()); //echo "Success!"."<br />"; //For the sake of stats tracking update the total isk on deposit. The payout script will subtract. $queryiskDeposit = mysql_query("SELECT iskDeposit FROM stats;") or die(mysql_error()); //echo "Executing the SQL command to query the ISK deposited : ".$queryiskDeposit."<br />"; $arrayiskDeposit = mysql_fetch_assoc($queryiskDeposit); $getiskDeposit = $arrayiskDeposit["iskDeposit"]; //echo "Got total isk on deposit of: ".$getiskDeposit."<br />"; $iskDeposit = $getiskDeposit+$deposit; //echo "Inserting: ".$iskDeposit." ISK"."<br />"; $importiskDeposit= "UPDATE stats SET iskDeposit='$iskDeposit';"; //echo "Executing the SQL command to desposit: ".$importBal."<br />"; mysql_query($importiskDeposit) or die(mysql_error()); //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } else{ //echo "There is no update for ".$name." because ".$lastRef." is not less then or equal to ".$currentRef."<br />"; //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } //echo "DEBUG for ".$name." lastRef ".$lastRef." and currentRef ".$currentRef."<br />"; //update the time that last update ran $today = date("Ymd G:i"); mysql_query("UPDATE stats SET iskLastUpdate='$today';") or die(mysql_error()); //echo "Updating Date to: ".$today; //echo "<br />"; //echo "<br />"; //echo "NEXT!<br />"; //echo "<br />"; } } ?> can anyone help me stop it duplicating the entries in the database please? Hello dear friends, say i've database table with (id,name) and want to add more informations by insert new names within an file for example has Code: [Select] $q1 = "INSERT INTO `mytable` VALUES (???,name1); mysql_query($q1) or die(mysql_error()." at row ".__LINE__); $q2 = "INSERT INTO `mytable` VALUES (???,name2); mysql_query($q2) or die(mysql_error()." at row ".__LINE__); ect..... how then it automatic detect the last id to go on after it ? some says use mysql_insert_id but i didn't understand how to apply it in this way also the example at php.net is bad not explain much please how can i use it thanks How can you debug to find out why it's not getting the mysql_insert_id number? I have it echoed all the queries and all with all the correct values from my form but the only problem is that its not getting the insert id number of the id. $query1 = "INSERT INTO `efed_bio` (charactername,username,posername,style_id,gender,status_id,division_id,alignment_id,sortorder) VALUES ('".$charactername."','".$username."','".$posername."','".$style."','".$gender."','".$status."','".$division."','".$alignment."','".$sort."')"; mysql_query($query1); $query1_id = mysql_insert_id(); echo $query1; echo $query1_id; $query2 = "INSERT INTO `efed_bio_allies` (bio_id) VALUES (".$query1_id.")"; mysql_query($query2); echo $query2; $query3 = "INSERT INTO `efed_bio_rivals` (bio_id) VALUES (".$query1_id.")"; mysql_query($query3); echo $query3; $query5 = "INSERT INTO `efed_bio_singles` (bio_id) VALUES (".$query1_id.")"; mysql_query($query5); echo $query5; I have two tables. The first with an auto-increment field of id and the second with a article_id field. I want to get the value of the auto-increment field in the first table and insert it into the article_id field of the second table (so they match). I am using the mysql_insert_id() command for the first time and I am wondering if I can run a query like this and turn it into a variable or if I need to use a SELECT query from the the mysql_insert_id() field from the first table before inserting it into the second table? Any feedback is appreciated. Thanks, kaiman Here is what I have so far (untested): // insert data into blog database $sql1="INSERT INTO $tbl_name1(author, title, content, date)VALUES('$author', '$title', '$content', NOW()) LIMIT 1"; $result1=mysql_query($sql1) or trigger_error("A mysql error has occurred!"); $article_id = mysql_insert_id (); // if successfully inserted data into database, redirect user if($result1){ header( "Location: http://www.mydomain.com/blog/add/success/" ); } else { header( "Location: http://www.mydomain.com/blog/add/error/" ); exit; } // insert data into blog categories database $sql2="INSERT INTO $tbl_name2(article_id, category)VALUES('$article_id', '$category' LIMIT 1"; $result2=mysql_query($sql2) or trigger_error("A mysql error has occurred!"); // if successfully inserted data into database, redirect user if($result2){ header( "Location: http://www.mydomain.com/blog/add/success/" ); } else { header( "Location: http://www.mydomain.com/blog/add/error/" ); exit; } When I run this Prepared Statement... // Build query. $q2 = "INSERT INTO member(email, activation_code, salt, hash, first_name, username, register_ip, register_hostname, location, created_on) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())"; // Prepare statement. $stmt2 = mysqli_prepare($dbc, $q2); // Bind variables to query. mysqli_stmt_bind_param($stmt2, 'sssssssss', $email, $activationCode, $salt, $hash, $firstName, $username, $ip, $hostName, $location); // Execute query. mysqli_stmt_execute($stmt2); // Capture New ID. $_SESSION['memberID'] = mysql_insert_id(); I am getting this error... Quote Warning: mysql_insert_id() [function.mysql-insert-id]: A link to the server could not be established in /Users/user1/Documents/DEV/++htdocs/05_Debbie/members/create_account.php on line 269 What am I doing wrong? Debbie hello, im asking for your help again. i have a problem with this mysql_insert_id() function im using. it's used to get the values of id's and insert it to a field of another table right?but in my case where i have 4 tables and using the function to get the unique id,it no longer gets the id on the third table which is supposed to be doing so that this id will be inserted to the field of the final table. these are dynamic textboxes im working on by the way..here's my php code: html Code: [Select] <html> <head> <script language="JavaScript"> function AddTextBox() { document.getElementById('container').innerHTML+='<input type="text" size="15" maxlength="15" name=block[]><br>'; } function AddTextBox2() { document.getElementById('container2').innerHTML+='<input type="text" size="15" maxlength="15" name=room[]><br>'; } </script> </head> <body> <form name="form1" method="post" action="adnew.php"> <input type="hidden" name="cid"> Course:<input type="text" name="course"> <input type="hidden" name="yid"> Year: <select name="year"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <table width="23%" border="0"> <tr> <td width="37%" height="1" colspan="2"> <input type="hidden" name="block_id"> Block: <input name="button" type="button" onClick="AddTextBox();" value="Add textbox"></td> </tr> <tr> <td height="21"><div id="container"></div></td> </tr> </table> <table width="23%" border="0"> <tr> <td width="64%">Room: <input name="button2" type="button" onClick="AddTextBox2();" value="Add textbox"></td> </tr> <tr> <td><div id="container2"></div></td> </tr> </table> <br><br><input type="Submit" name="submit" value=" Add "> </form> </body> </html> php Code: [Select] <?php include("dbcon.php"); ?> <?php $id_c=$_POST['cid']; $block=$_POST['block']; $block_id=$_POST['block_id']; $room=$_POST['room']; $intblock=0; $introom=0; $sql=mysql_query("INSERT INTO course VALUES ('$id_c','$_POST[course]')") or die (mysql_error()); $id_c = mysql_insert_id(); $sql=mysql_query("INSERT INTO year VALUES ('$_POST[yid]','$id_c','$_POST[year]')") or die (mysql_error()); $_POST['yid'] = mysql_insert_id(); while(count($block)>$intblock) { if (($block[$intblock]<>"")){ $sql=mysql_query("INSERT INTO block VALUES ('$block_id', '$_POST[yid]', '".$block[$intblock]."')") or die (mysql_error()); mysql_query($sql); } else{ echo "Block ".($intblock+1)." is missing values and cannot be inserted."; } $intblock=($intblock+1); } $block_id = mysql_insert_id(); while (count($room)>$introom) { if (($room[$introom]<>"")){ $sql=mysql_query("INSERT INTO room VALUES ('$block_id', '".$room[$introom]."')") or die (mysql_error()); // this is the 4th table.. mysql_query($sql); } else{ echo "Room ".($introom+1)." is missing values and cannot be inserted."; } $introom=($introom + 1); } echo "Successfully added."; echo "<br><a href='index.php'>Add another</a>"; ?> Quote $block_id = mysql_insert_id(); this is what i'm having problems with.. Quote $sql=mysql_query("INSERT INTO room VALUES ('$block_id', '".$room[$introom]."')") or die (mysql_error()); and this is for my 4th table.. i have found out that you have to put the function after an INSERT command,but in my case, i have a switch statement and after i tried putting it inside the switch, i get a message that says "duplicate entry 1 for b_id...etc.." any suggestions?advise? I get mysql_insert_id problem. It returns 0. I do not know how to fix it. Please tell me. Thank you very much. <?php session_id(); session_start();?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> <?php include("connection.php"); $subtotal=$_POST['subtotal']; $tax=$_POST['tax']; $total=$_POST['total']; $today=date("Y-m-d"); $email=$_SESSION['email']; $od=mysql_insert_id(); $number=$_POST['number']; $name=$_POST['name']; $month=$_POST['month']; $year=$_POST['year']; $code=$_POST['code']; $method=$_POST['type']; $add1="select * from customer where email='$email'"; $add2=mysql_query($add1); $add3=mysql_fetch_array($add2); extract($add3); $qiu1="INSERT INTO test (oid) VALUES ('$email')"; $qiuzhen=mysql_query($qiu1); $orderid=mysql_insert_id(); $query44="INSERT INTO income (subtotal,tax,total,time,email,address,credit,name,month,year,code,method,custid) VALUES ('$subtotal','$tax','$total','$today','$email','$add1',$number,'$name','$month','$year','$code','$method','$orderid')"; $result=mysql_query($query44); echo "successful!"; $orderid=mysql_insert_id(); echo "$email"; echo "$total"; $sessid=session_id(); $qu="select * from carttemp where sess='$sessid'"; $result=mysql_query($qu); while($w=mysql_fetch_array($result)){ extract($w); $query7="INSERT INTO try (prodnum,quan,custnum) VALUES ('$prodnum','$quan','$custid')"; $iii=mysql_query($query7) or (mysql_error()); } ?> </body> </html> Hi all, i'm a bit more than a newbie. Here's the scenario. I have a page with tabbed navigation. On each tab there's a form (diving centers, teachers, and so on). Each form has a submit button with a unique name. Every submit button is processed by a series of if statements in an external included php file. As you can see in my code below what the file does is to process the if statements based on the submit pressed. It' important to notice that a JS script checks that the first form is filled with all the infos. If not is not possible to proceed to complete all the others. On the first form the user can register general information. Obviously there's an Id field (auto increment) that i grab with mysql_nsert_id. Also obvious is the fact that, for query reasons, i want to store the grabbed id in an id field present in all the tables of my database. The tables get the data from the various forms displayed on the tabbed navigation. Here's the code of the included file (notice that i use to start with a simple coding to test everything 's working fine) <?php require_once('Connections/Scubadiving.php'); if (!empty($_POST['theButton'])) { $nome=$_POST["nome"]; $indirizzo=$_POST["indirizzo"]; $insertSQL = "INSERT INTO centrisub (nome, indirizzo) VALUES ('$nome' , '$indirizzo')"; mysql_select_db($database_Scubadiving, $Scubadiving); $Result1 = mysql_query($insertSQL, $Scubadiving) or die(mysql_error()); $last_id = mysql_insert_id ($Scubadiving); } if (!empty($_POST['istruttori'])) { echo $_SESSION["$last_id"]; $insertSQL = "INSERT INTO istruttori (nome, data_nascita, curriulum, altre_info, idcentrisub) VALUES ('$_POST[nome]','$_POST[data_nascita]','$_POST[curriculum]','$_POST[altre_info]','$last_id')"; mysql_select_db($database_Scubadiving, $Scubadiving); $Result1 = mysql_query($insertSQL, $Scubadiving) or die(mysql_error()); } ?> What i don't understand is why $last_id is not passed form the first if statment (processed when the user submit the generel infos form) to the other if statement (in this case the teachers form). I've tried also with $_SESSION (trying to assign $last_id) but no success. (Probably because i don't know exactly how to use it) Hope everything's clear. What i'm missing ? Thanks in advance for your help. Hello there, well basically what this function does is look at all the entry's to find a unused port in the database but when I run the function the first time if the table is empty mysql_insert_id works fine, but then if I run it again the mysql_insert_id keeps returning 0, I am using it immediately after the query but its not working properly, can anybody shed some ideas into the matter, anything is appreciated!, thanks for your time!: function addServerToBuildPool($ServerGame, $ServerOwner, $ServerSlots, $ServerBox) { $Server = mysql_fetch_array(mysql_query("SELECT * FROM xhost_boxs WHERE box_id = '".mysql_real_escape_string($ServerBox)."'")); $AddServer = mysql_query("INSERT INTO xhost_servers (server_game, server_slots, server_owner, server_ip, server_is_setup) VALUES('".mysql_real_escape_string($ServerGame)."', '".mysql_real_escape_string($ServerSlots)."', '".mysql_real_escape_string($ServerOwner)."', '".mysql_real_escape_string($Server['box_ip'])."', 'No')"); $ServerID = mysql_insert_id(); $FindPort = mysql_query("SELECT server_port FROM xhost_servers ORDER BY server_id ASC"); $Port = 0; while($row = mysql_fetch_assoc($FindPort)) { $Port = ($Port == 0)? $row['server_port'] : $Port; if($row['server_port'] != $Port) { break; } $Port++; } mysql_query("UPDATE xhost_servers SET server_port = '".$Port."' AND server_username = 'server".$ServerID."' AND server_password = '".rand(5000000, 900000000)."' WHERE server_id = '".$ServerID."'") or die(mysql_error()); } after inserting data i get 0 sometimes i created a mysql_connect for it Code: [Select] <?php $maincon = mysql_connect('local', "root", "root"); mysql_select_db("root"); then //insert and $success = mysql_query($query); echo $ref_id = mysql_insert_id($maincon); ?> $ref_id is returned as 0, although the connection is there var_dumping the query returns the values Set up Windows Vista * XAMPP 1.7.3, including: * Apache 2.2.14 (IPv6 enabled) + OpenSSL 0.9.8l * MySQL 5.1.41 + PBXT engine * PHP 5.3.1 * phpMyAdmin Ultimate objective: I want to insert session data into multiple tables whilst ensuring that the data is in the appropriate column. Problem: I managed to insert the data into the correct tables and column, but after reading various forums I have been given the impression that if I was to have multiple site users the data's columns could get muddled up if they execute the script at the same time (hope I'm making sense, say if I'm not). The suggested method was mysql_insert_id() but I do not know how to make this work with in conjunction with sprintf(). As I said the script worked before I added the code with the star by it in an attempt to reach my ultimate objective. <?php //let's start our session, so we have access to stored data session_start(); session_register('membership_type'); session_register('terms_and_conditions'); include 'db.inc.php'; $db = mysql_connect('localhost', 'root', '') or die ('Unable to connect. Check your connection parameters.'); mysql_select_db('ourgallery', $db) or die(mysql_error($db)); //let's create the query $query = sprintf("INSERT INTO subscriptions ( name, email_address, membership_type) VALUES ('%s','%s','%s')", mysql_real_escape_string($_SESSION['name']), mysql_real_escape_string($_SESSION['email_address']), mysql_real_escape_string($_SESSION['membership_type'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); *mysql_real_escape_string($_SESSION['name']) = mysql_insert_id($db);* $query = sprintf("INSERT INTO site_user_info ( terms_and_conditions, name_on_card, credit_card_number ) VALUES ('%s','%s','%s')", *mysql_real_escape_string($_SESSION['name']),* mysql_real_escape_string($_SESSION['terms_and_conditions']), mysql_real_escape_string($_POST['name_on_card']), mysql_real_escape_string($_POST['credit_card_number']), mysql_real_escape_string($_POST['credit_card_expiration_data'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); *mysql_real_escape_string($_SESSION['credit_card_number']) = mysql_insert_id($db);* $query = sprintf("INSERT INTO card_numbers ( credit_card_expiration_data) VALUES ('%s')", *mysql_real_escape_string($_POST['credit_card_number']),* mysql_real_escape_string($_POST['credit_card_expiration_data'])); $result = mysql_query($query, $db) or die(mysql_error($db)); echo '$result'; ?> All the other facets of the script work but I get the following error message with the above script: Fatal error: Can't use function return value in write context in C:\x\xampp\htdocs\form_process.php on line 27 But it's not so much the error message its the ultimate objective. Any help appreciated. If one inserts acute letters, grave letters, ampersands and accented letters in xhtml they show perfectly on the page. However if one uses insert or rss feed they show as � or a square. How does one make them show correctly. I am trying to make a simple CMS, the table is created with this command(using php): Code: [Select] private function buildDB() { $sql = <<<MySQL_QUERY CREATE TABLE IF NOT EXISTS newcore ( id MEDIUMINT NOT NULL AUTO_INCREMENT, title VARCHAR(128), menutitle VARCHAR(128), bodytext TEXT, json VARCHAR(1024), children VARCHAR(128), template INTEGER, created VARCHAR(100), PRIMARY KEY (id) ) ENGINE=MyISAM; MySQL_QUERY; return mysql_query($sql); } everything works fine, insert, delete, select, etc. But when I update a row, the update is also done, but another row is created with the same values, but of course a new id. I do the update this way: Code: [Select] $created = time(); $sql = 'UPDATE newcore SET title="'.$title.'", menutitle="'.$menutitle.'", bodytext="'.$bodytext. '", json="'.$json.'", children="'.$children.'", template="'.$template.'", created="'.$created.'" WHERE id='.$req['id']; mysql_query($sql); All the values are entered by myself, so there is no possibility of problem in values to make it function like that. Please help me, It's driving me insane! Thanks in advance. Is it possible - and reasonable - to have one Form which allows Users to create a new record (i.e. do an INSERT) and which also allows Users to modify an existing record (i.e. do an UPDATE)? When a User registers at my website, not only do they create a record in the "member" table, but one of the required fields is "First Name". What that means is that when I allow Users to edit details in their Profile - most of which were not included in registration to streamline the process - I don't have to worry about doing an INSERT, because I already created a "member" record and on the "Edit Details" page the first field is "First Name" so that is a hook so to speak where they can enter more info about themselves like... Code: [Select] - Location - Date of Birth - Interests - Bio and so on... So here is my problem which I just discovered... Also in my User Profile, I allow Users to answer several open-ended questions like... Code: [Select] 1.) Why did you decide to start your own business? 2.) What advice would you share with others on what NOT to do? The problem is that these questions exist in the "bio_question" table and the answers that I am trying to get from Users will be stored in the "bio_answer" table but no record currently exists?! So do I need both an "INSERT Answers Form" *and* an "UPDATE Answers Form", or can I combine things into one form?! Hope that all makes sense?! Debbie I tried inserting a town into my database but only the first word gets inserted?! eg: Abbots Langley only Abbots gets inserted?! Code: [Select] if(isset($_POST["register"])) { // Your code here to handle a successful verification $RSTOWN = $_POST['rsTown']; $rsGender = $_POST['rsGender']; $RSUSER = $_POST['RSUSER']; $RSPASS = $_POST['RSPASS']; $rsEmail = $_POST['rsEmail']; $rsMobile = $_POST['rsMobile']; $rsAge = $_POST['rsAge']; $to = 'info@mypubspace.com, '.$rsEmail; //define the subject of the email $subject = 'Welcome '.$RSUSER.' to My Pub Space'; // message $message = ' <html> <head> <title>'.$subject.'</title> </head> <body> <table> <tr> <td>Name:</td> <td>'.$RSUSER.'</td> </tr> <tr> <td>Email:</td> <td>'.$rsEmail.'</td> </tr> <tr> <td>Town:</td> <td>'.$rsTown.'</td> </tr> <tr> <td>Telephone:</td> <td>'.$rsMobile.'</td> </tr> <tr> <td>Age:</td> <td>'.$rsAge.'</td> </tr> <tr> <td>Password:</td> <td>'.$RSPASS.'</td> </tr> </table> </body> </html> '; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= 'To:' .$to. "\r\n"; $headers .= 'From:' .$rsEmail. "\r\n"; // Mail it mail($to, $subject, $message, $headers); $sql = "INSERT INTO members_copy (RSTOWN, RSGENDER, RSUSER, RSPASS, RSEMAIL, RSMOBILE, RSAGE) VALUES ('$rsTown', '$rsGender', '$RSUSER', '$RSPASS', '$rsEmail', '$rsMobile', '$rsAge');"; //echo $sql; mysql_query($sql); hi, i made my own page, but when i do an insert using mysql, jquery and php, the arabic text does not show properly it is a comments page. here is the DB structure Code: [Select] CREATE TABLE IF NOT EXISTS `app_comments` ( `comment_id` int(20) NOT NULL auto_increment, `comment` text NOT NULL, `user_id` int(20) NOT NULL, `comment_date` date NOT NULL, `app_id` int(20) NOT NULL, PRIMARY KEY (`comment_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ; here is the jquery piece that transfers to php code. Code: [Select] function submit_comment(){ $(".post_comments_button").click(function() { var post_comments = $('.post_comments').val(); var app_id = $('#app_id').val(); //alert (app_id); if(confirm('Add Comment?')) { var string = "task=add_comment&app_id=" + app_id + "&comment="+post_comments; $.ajax({ url : "appajax.php", type : "POST", data : string, success : function(data) { alert(data); window.location.reload(true); } }); } /**/ }); }and here is the acutal insert code in php $new_appquery = 'INSERT INTO app_comments (comment, user_id, app_id,comment_date) VALUES ("' . $comment . '",' . $user_id . ', ' . $app_id . ',NOW());'; and the actual problem is, the arabic text shows like this in my application: Quote بالتوفيق للريال how can i solve this issue? Hi, I m doing some work for my self an because of that i been reading a lot arround about PHP, and theres something that i would like to ask a bit of enlightenment. So my question is as the title says about html form's using php to insert data into mysql, i been reading tutorials arround the interwebs and even made afew successful tests, but pretty much all tutorials use 2 files to accomplish this the html file with the form and an insert.php where the actual code is stored so this made me think is this how usually it's done? in over all you will have 1 file for the form, 1 for the insert, 1 for the edit php code and 1 for delete. How do you guys usually do it? PS: one of the tests i did was making 1 single file with all these using an switch. My interest in making this question is solo to learn how other people do it to see if i m in the right way. Thanks in advance. Hi i have a drop down menu for date which is meant to insert all 3 values into a date column bt is only sending the year how can i fix it <select name="date_of_birth"> <option value="1">January <option value="2">February <option value="3">March <option value="4">April <option value="5">May <option value="6">June <option value="7">July <option value="8">August <option value="9">September <option value="10">October <option value="11">November <option value="12">December </select> <select name="date_of_birth"> <option value="1">1 <option value="2">2 <option value="3">3 <option value="4">4 <option value="5">5 <option value="6">6 <option value="7">7 <option value="8">8 <option value="9">9 <option value="10">10 <option value="11">11 <option value="12">12 <option value="13">13 <option value="14">14 <option value="15">15 <option value="16">16 <option value="17">17 <option value="18">18 <option value="19">19 <option value="20">20 <option value="21">21 <option value="22">22 <option value="23">23 <option value="24">24 <option value="25">25 <option value="26">26 <option value="27">27 <option value="28">28 <option value="29">29 <option value="30">30 <option value="31">31 </select> <select name="date_of_birth" id="year"> <?php $year = date("Y"); for($i=$year;$i>$year-50;$i--) { if($year == $i) echo "<option value='$i' selected>Current Year</option>"; else echo "<option value='$i'>$i</option>"; } ?> |