PHP - Nothing Inserted No Error
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); } ?> Similar TutorialsWonder 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 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? 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);
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"; 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>'; //} ?> 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; } ?> Code: [Select] <?php //Register 1.0.1 include("function.php"); connect(); $num = 0; if(isset($_POST['submit'])) { if($_POST['username'] == '' || $_POST['password1'] == '' || $_POST['password2'] == '') { $num = 1; echo "Please supply all fields;"; exit(); } elseif(strlen($_POST['username']) > 25) { $num = 1; echo "Username must be under 25 characters long;"; exit(); } elseif(strlen($_POST['password1']) > 16) { if(strlen($_POST['password2']) >16) { $num = 1; echo "Password are over 16 characters long;"; exit(); } $num = 1; echo "Passwords are not equal"; exit(); } elseif($_POST['password1'] != $_POST['password2']) { $num = 1; echo "Passwords are not equal;"; exit(); } } else { if(isset($_POST['submit'])) { $username = $_POST['username']; safe($username); if($_POST['password1'] = $_POST['password2']) { $password = $_POST['password']; password($password); echo "INSERT INTO user (username, password) VALUES ('$username','$password')"; } else { echo "Passwords are not equal; Double Take";//Yes Double Take is a military term exit(); } } } ?> <HTML> <form action="register.php" method="post"> Username:<input type="text" name="username"> <br> Password:<input type="password" name="password1"> <br> Password Check:<input type="password" name="password2"> <br> <input type="submit" name="submit" value="Register!"> </HTML> Here is where I put the code: if(isset($_POST['submit'])) { $username = $_POST['username']; safe($username); if($_POST['password1'] = $_POST['password2']) { $password = $_POST['password']; password($password); echo "INSERT INTO user (username, password) VALUES ('$username','$password')"; } else { echo "Passwords are not equal; Double Take";//Yes Double Take is a military term exit(); } I used it like that to narrow it down. And I still do not understand the issue, are there any other issues? [attachment deleted by admin] 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); ;?> Hi Guys, actually I'm doing hard with this code. the fact is that Im inserting data (name, phone number, nss) and im doing a select to get the id number where nss is like $nss (. I don`t know why I can`t receive data, i think the fact is that all the code is inside an if statement) But that is why im here guys. In adittion I tryed to get the max id in order to print into mail function. But I couldn't . This is my code...
************************************************************************************************************ //Database connection done perfectly $mysqli = mysqli_connect( "****", "***", "***", "***");
************************************************************************************************************ // Im working with bots and the intent received is this, in addition i get variables correctly.
************************************************************************************************************ //here im inserting the variables in the correct order. The database is getting the values correctly too.
************************************************************************************************************
************************************************************************************************************
//here is the section when im going to select the id from the table, where the nss number is equal to the nss variable number that i've putted (but idk if the insert is done at this point....
************************************************************************************************************ For example i'm getting the mail, the name and lastname correctly from my function (which gets the parameters and turn the information in readable characters to php)
$to = $email; } ************************************CODE DONE ***********************************************************
So guys, Idk what is happening here, I tryed lot of things but when im get the email I dont get the id value..... I think is because the insert hasn't been completed while the if is open..... In adition I wanto to ask you guys if somebody knows how to get correctly the data from this code... Firstly I was trying to get the max id from my table and then plus 1 to increase the number. and in that order put the id by myself or atleast get the value in that way. I tryed closely, but i finish getting the array value.. I going to show my code...
function obtener_Id(){ I have tried to run my code and it works. I am not getting any error message but when I checked my database nothing was added. Code: [Select] <?php session_start(); include '../Database/connection.php'; if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } $filename = $_FILES["file"]["tmp_name"]; $fd = fopen ($filename, "r"); $data = fread ($fd,filesize ($filename)); fclose ($fd); $delimiter = "\n"; $output = explode($delimiter, $data); foreach($output as $var) { $tmp = explode(".", $var); $question = $tmp[0]; $choice1 = $tmp[1]; $choice2 = $tmp[2]; $choice3 = $tmp[3]; $choice4 = $tmp[4]; $answer1 = $tmp[5]; $answer2 = $tmp[6]; $answer3 = $tmp[7]; $answer4 = $tmp[8]; $sql = "INSERT INTO question SET Que_Question='$question', Que_Choice1='$choice1', Que_Choice2='$choice2', Que_Choice3='$choice3', Que_Choice4='$choice4', Que_Answer1='$answer1', Que_Answer2='$answer2', Que_Answer3='$answer3', Que_Answer4='$answer4', Tes_ID='$_SESSION[Tes_ID]'"; mysql_query($sql); } ?> My text file holds Quote What is the sky.where.how.wen.one.0.0.1.0 What colour.where.what.how.more.0.0.1.0 whats wrong in here for i get query failed everytime i submit the form? Code: [Select] //Create INSERT query $qry = "INSERT INTO class_members (user_name, passwrd, f_name, l_name, email, gender, date) VALUES('$user_name','".md5($_POST['password'])."','$f_name','$l_name','$email', '$gender','gmdate($date)',)"; $result = @mysql_query($qry); //Check whether the query was successful or not if($result) { header("location: register-success.php"); exit(); }else { die("Query failed"); } I only see one "mysql_query($memberquery);" Yet the record is inserted 4 times when I check the db. Anyone see why? Thank you for your time! Code: [Select] <?php $link_register = 1; session_start(user); include("header.php"); $firstname = $_SESSION['firstname']; $middleinitial = $_SESSION['middleinitial']; $lastname = $_SESSION['lastname']; $phone = $_SESSION['phone']; $email = $_SESSION['email']; $street = $_SESSION['street']; $city = $_SESSION['city']; $state = $_SESSION['state']; $categoryArray = $_SESSION['categoryArray']; $gender = $_SESSION['gender']; $con = mysql_connect("localhost", "root", ""); if (!$con) { die("Could not connect: ". mysql_error()); } //The database is selected with the mysql_select_db() function. mysql_select_db("hobbyclub", $con); //put the data insert into a varaible so it can be checked later $memberquery = "INSERT INTO member (firstname, middleinitial, lastname, phone, email, street, city, state, gender) VALUES ('$firstname', '$middleinitial', '$lastname', '$phone', '$email', '$street', '$city', '$state', '$gender')"; // if ($categoryArray){ // foreach ($categoryArray as $category){ // $categoryString .= "'$".$category."',"; // } // } // $categoryquery = "INSERT INTO category (categoryname) VALUES('$categoryString')"; // $categoryquery = "INSERT INTO category (categoryname) VALUES(".$categoryString.")"; //insert the data mysql_query($memberquery); ?> The commented out block of code is just me trying to figure out how to insert an array into the db. 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 Shouldn't the following stop a blank row from being inserted into mysql? I have a description and a date but it still keeps putting a blank row before my insert and I've tried everything.... if($myvar != ''){ mysql_query("INSERT IGNORE INTO products (description, time) VALUES('$myvar',NOW() ) ") or die(mysql_error()); 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. I 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. Ugh. Ive been asking so many questions, betcha already know my name. Hahah. Anyways, I know I already asked a question like this, but this is different. One of the values I am trying to insert into a database is simply not working. Here is the columnes in my mysql database: c_id commet story user date_added star Every value but 'commet' is getting inserted into database. NO error, no mysql errror. I have racked my brain trying to figure out what is wrong with the script. Here is my code: Code: [Select] <?php $idget = $_GET['id']; mysqlConnect(); //submit story if(isset($_POST['submit'])) { $com_form = mysql_real_escape_string(bb($_POST['commet'])); $rat_form = $_POST['rat']; $story_form = $idget; $user = $_SESSION['user']; $date = date("Y-m-d"); $query1 = " INSERT INTO story_commets(star, story, user, date_added, commet) VALUES($rat_form, '$story_form', '$user', '$date', '$com_form') "; mysql_query($query1) or die(mysql_error()); //} } // desplay reviews $query3 = " SELECT * FROM story_commets WHERE story = '$idget' ORDER BY date_added "; $select3 = mysql_query($query3) or die(mysql_error()); //$x=1; $ratav = array(); //if(mysql_num_rows($select3) == 0) //{ echo '<div id="message"> No Reviews Yet.... <>'; //} //else //{ while($rows3 = mysql_fetch_assoc($select3)) { $commetdb = $rows3['commet']; $user_com_db = $rows3['user']; $datedb = $rows3['date_added']; $stardb = $rows3['star']; //get profile picture $query4 = " SELECT * FROM login_info WHERE user = '$user_com_db' "; $select4 = mysql_query($query4) or die(mysql_error()); $rows4 = mysql_fetch_assoc($select4) or die(mysql_error()); $profile_pic = $rows4['profile_picture']; $user_id = $rows4['id']; echo " <div class='rev_cont'> <div class='info'> <img src='$profile_pic' /> <a href=?p=profile&id=$user_id> $user_com_db </a> <> <br /> <div class='rev'> <strong> $stardb/10 </strong> <br /> $commetdb <> <div id='date'> <em> Date Added: $datedb </em> <> <> <hr /> "; $ratav[]=$stardb; } $sum = array_sum($ratav); $count = count($ratav); $av = $sum / $count; $avf = round($av, 1); echo"<div id='message'> Rating Avarage: $avf /10 <>"; //} if (isset($_SESSION['user'])) { echo" <p> Did you like this story? Did you hate it? Give it a rating and let the author know!</p> <form action='?p=review&id=$idget' method='post' target='_self'> <label> Your rating is on a scale of 1-10 </label> <select name='rat'> <option> 1 </option> <option> 2 </option> <option> 3 </option> <option> 4 </option> <option> 5 </option> <option> 6 </option> <option> 7 </option> <option> 8 </option> <option> 9 </option> <option> 10 </option> </select> <label> Commets: </label> <textarea name='commet' cols='70' rows='9'></textarea> <input name='story' type='hidden' value='$idget' /> <br /> <input type='submit' value = 'Post' name='submit' /> </form> "; } else { echo "<div id='message'> Sign in to post a review! <>"; } ?> Here are the specifics if you want it. Here is the response part of the code: Code: [Select] <?php if(isset($_POST['submit'])) { $com_form = mysql_real_escape_string(bb($_POST['commet'])); $rat_form = $_POST['rat']; $story_form = $idget; $user = $_SESSION['user']; $date = date("Y-m-d"); $query1 = " INSERT INTO story_commets(star, story, user, date_added, commet) VALUES($rat_form, '$story_form', '$user', '$date', '$com_form') "; mysql_query($query1) or die(mysql_error()); //} } ?> Here is the form part of my code: Code: [Select] <?php if (isset($_SESSION['user'])) { echo" <p> Did you like this story? Did you hate it? Give it a rating and let the author know!</p> <form action='?p=review&id=$idget' method='post' target='_self'> <label> Your rating is on a scale of 1-10 </label> <select name='rat'> <option> 1 </option> <option> 2 </option> <option> 3 </option> <option> 4 </option> <option> 5 </option> <option> 6 </option> <option> 7 </option> <option> 8 </option> <option> 9 </option> <option> 10 </option> </select> <label> Commets: </label> <textarea name='commet' cols='70' rows='9'></textarea> <input name='story' type='hidden' value='$idget' /> <br /> <input type='submit' value = 'Post' name='submit' /> </form> "; } else { echo "<div id='message'> Sign in to post a review! <>"; } ?> Its probably something really mundane. HelP! 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 After I've successfully inputted something in my script and then click refresh in Chrome with "Right Click -> Reload", the same thing that I've inputted before gets re-inserted AGAIN into the database, thus resulting in multiple versions of the same thing in the MySQL database. How can I prevent that? p.s. Chrome is warning with a pop up of repeated action, and when I then click continue the repeated insertion of the data occurs, and I'd like to prevent the repeated insertion. hello every body...
two
I'm creating an IPN in paypal for my membership site but the problem I'm facing is that on successfull verification of the purchase, four rows are getting inserted in the database...
The code is
<?php require '../db.php'; $paypalmode = '.sandbox'; $req = 'cmd=' . urlencode('_notify-validate'); foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $req .= "&$key=$value"; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr'); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: www'.$paypalmode.'.paypal.com')); $res = curl_exec($ch); curl_close($ch); if (strcmp ($res, "VERIFIED") == 0) { $transaction_id = $_POST['txn_id']; $payerid = $_POST['payer_id']; $firstname = $_POST['first_name']; $lastname = $_POST['last_name']; $payeremail = $_POST['payer_email']; $paymentdate = $_POST['payment_date']; $paymentstatus = $_POST['payment_status']; $mdate= date('Y-m-d h:i:s',strtotime($paymentdate)); $otherstuff = json_encode($_POST); $date = date("y-m-d"); $q = $pdo->connect()->query("INSERT INTO payment (mid,username,amount,paypal_id,txn_id,received_date) VALUES('{$_SESSION['user_id']}','{$_SESSION['uname']}','{$_POST['mc_gross']}','{$_POST['payer_email']}','{$_POST['txn_id']}','$date')"); $q->execute(); $q1 = $pdo->connect()->query("UPDATE members SET amount_loaded = amount_loaded + {$_SESSION['amount']} WHERE mid = '{$_SESSION['user_id']}'"); $q1->execute(); //header("Location: funds.php"); echo "verified"; } ?>two for the payment and in the members table, the amount is getting doubled. (i.e if anybody purchases For $2, it shows $4 in the database....) Any help will be really appreciated... |