PHP - Mysql_insert_id Problem
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> Similar Tutorialshello, 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? 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 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 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; 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()); } 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; } 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. Guys thanks for helping me solve the problem i had but now i have another problem and i am lost. i have included the code below for you to have overview.
This is the code:
<table style="width:100%; margin-left:auto; margin-right:auto"> I have having a problem getting a mysql query to work. If I just use mysql_query it looks like this and works fine: INSERT INTO schedule (schedule_pk, schedule_month, schedule_day, schedule_year, schedule_hour, schedule_minute, schedule_type, employeenumber) VALUES ( NULL, 10, 10, 1999, 12, 6, 'DayIn', 3); If I put it through mysql_real_escape_string it turns it to this and does not work when I put it into mysql_query: INSERT INTO schedule (schedule_pk, schedule_month, schedule_day, schedule_year, schedule_hour, schedule_minute, schedule_type, employeenumber) VALUES ( NULL, 10, 10, 1999, 12, 6, \'DayIn\', 3); aka: $query = "INSERT INTO...." mysql_query($query); that works, but: $query = "INSERT INTO...." $sqlQuery = mysql_real_escape_string($query, $con); mysql_query($sqlQuery); results in the error. mysql_query($query); The error is: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'DayIn\', 3)' at line 1 Hi, i use mysql_real_escape_string() function when insert in db, but when echo i use htmlentities($var, ENT_QUOTES, "UTF-8") Now problem is '\ in that text. In db it write text with single quote with \, example That\'s wrong, and when echo it show just the same like in db.. How can i fix this ? Hows it going guys. I am currently having a problem. I had a program that worked. I migrated the website and now the program is broken. Any time i try to run it, i get this error: Quote Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/thegoo20/public_html/class/wordgame/wordgame.php on line 31 Here is the code at that point: Code: [Select] function changeword(){ $result = mysql_query("Select words from CurrentWords"); $totalwords = array(); while ($row = mysql_fetch_array($result)){ $totalwords[] = $row["words"]; } $_SESSION['word'] = $totalwords[rand(0, count($totalwords)-1)]; $_SESSION['scrambled'] = str_shuffle($_SESSION['word']); } where line 31 is the while statement. Any help would be appreciated. Thanks Okey so i made a table that you put your name,author,and message when you submit it , it echoes a table with the name,author and message written (and it also echoes a delete buttom,so delete this post oif necessary) im new to php and i have been with this problem for a couple of weeks so i guess its time to ask for some help the problem is that i dunnot know how to make my delete buttom work! i tried if statement but it dosent work i also tried ternary operation and dint work :S i read that there is something like $post[ID](and this is supposed to get the ID of the post submmited, and delete it) im not sure, im so confused! help! XD this is the code <?php $tittle=$_POST['tittle']; $author=$_POST['author']; $message=$_POST['message']; if ($_POST['submitnews']){ $currentdate= date("y-m-d"); $currenttime=date("H:i:s",strtotime("-6 hours")); $post=mysql_query("INSERT INTO news VALUES('','$tittle','$author','$message','$currentdate','$currenttime')"); echo"Posted!"; } $select=mysql_query("SELECT * FROM news ORDER BY id DESC"); while ($row= mysql_fetch_assoc($select)) { $id=$row['id']; $tittle=$row['tittle']; $author=$row['author']; $message=$row['message']; $date=$row['date']; $time=$row['time']; if ($_SESSION['admin']) { echo " <table width='488px' id='news_table'> <tr> <td> </td> <td> <center><font size='5'>$tittle</font></center><br> </td> </tr> <tr> <td> </td> <td> $message </td> </tr> <tr> <td> </td> <td> <font size='1'>Posted By:<font color='green'>$author</font> on <font color='gray'>$date</font> at <font color='gray'>$time</font></font> <input name='delete' type='submit' value='delete'> <td> </td> </tr><br><br> </table>"; I do not receive email for my published php file which is: <?php ///// easend.php ///// $youremail = "acdelco40108@yahoo.com"; /*put the email address here, between quotes, the email address you want the message sent to*/ $to = $youremail; $email = $_POST['EMail']; $name2 = $_POST['Name']; $street2 = $_POST['Street']; $city2 = $_POST['City']; $state2 = $_POST['State']; $zip2 = $_POST['Zip']; $Phone = $_POST['Home_Phone']; $Cell = $_POST['Cell_Phone']; $education = $_POST['email1']; $comments = $_POST['email2'] ; $headers = "From:" . $email; $fields = array(); $fields{"Name"} = "Name"; $fields{"Street"} = "Street"; $fields{"City"} = "City"; $fields{"State"} = "State"; $fields{"Zip"} = "Zip"; $fields{"Home_Phone"} = "Home Phone"; $fields{"Cell_Phone"} = "Cell Phone"; $fields{"EMail"} = "Email"; $fields{"email1"} = "Education"; $fields{"email2"} = "Comments"; $subject = "We have received the following information from your employment application"; $body = "We have received the following information from your employment application:\n\n"; foreach($fields as $a => $b) { $body .= sprintf("%20s: %s\n",$b,$_POST[$a]); } mail ($to, $subject, $body, $headers); //send mail to owner #end create email vars $headers = "From:" . $to; mail ($email, $subject, $body, $headers); //send mail to user #end create email vars echo "<head><META HTTP-EQUIV=\"Refresh\" CONTENT=\"2; URL=ThankYou.html\"></head>"; ?> I am trying to understand PHP OOP and I have some code that is not working. here is the error code. Code: [Select] Parse error: parse error, expecting `T_FUNCTION' in C:\wamp\www\testing\armor_lib.php on line 11 And here is the armor_lib.php file: <?php class armor { // Head public $head; public $torso; public $pants; public $gloves; public $boots; // new stuff here class head extends armor { function __construct($head){ $this->set_head($head); } } // Torso class torso extends armor { function __construct($torso){ $this->set_torso($torso); } } // Pants class pants extends armor { function __construct($pants){ $this->set_pants($pants); } } // Gloves class gloves extends armor { function __construct($gloves){ $this->set_gloves($gloves); } } // Boots class boots extends armor { function __construct($boots){ $this->set_boots($boots); } } } ?> And here is the php in the armor.php file I have: <?php $head = new armor("Leather Helm"); $torso = new armor("Leather Shirt"); $pants = new armor("Leather Pants"); $gloves = new armor("Chain Mail Gloves"); $boots = new armor("Leather Boots"); echo "You are wearing: " . $head->get_head() . "on your Head"; echo "<br />"; echo "You are wearing: " . $torso->get_torso() . "on your Torso"; echo "<br />"; echo "You are wearing: " . $pants->get_pants() . "on your Legs"; echo "<br />"; echo "You are wearing: " . $gloves->get_gloves() . "on your Hands"; echo "<br />"; echo "You are wearing: " . $boots->get_boots() . "on your Feet"; ?> Any Help in understanding this will be much appreciated. Thanks. I am trying to save this an an xml document but am getting this error when I try to open the xml file "feed.xml" - "XML Parsing Error: no element found" $xml = '<rss version="2.0"> <channel> <title> RSS Feed</title> <link></link> <description>the best industry-lead opinions</description> <language>en-us</language> </channel> </rss>"; $xml2 = new DOMDocument('1.0'); $xml2->Load($xml); $xml2->save("feed.xml"); I Have An error on line 42 not sure what it is can any one tell? $foundnum = mysql_num_rows($run); |