PHP - How To Use This ! Mysql_insert_id
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 Similar TutorialsHow 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; 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 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()); } 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? 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. 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; } 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> 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 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. |