PHP - Insert Duplication
As part of an image gallery I am trying to INSERT data into a table to make accessible the relevant info of individual images - the problem I have encountered is that each query seems to be being inserted twice, and I can't figure out why. The code =
Code: [Select] <?php /*============================================== Connect to MySQL and select the correct database ==============================================*/ mysql_connect("localhost", "uname", "pwd") or die(mysql_error()); echo "Connected to MySQL<br />"; mysql_select_db("gallery_db") or die(mysql_error()); echo "Connected to Database gallery_db.<br />"; /*============================================= Include the files needed to undertake this task =============================================*/ include("functions.php"); /*========================= Set up arrays and variables =========================*/ $store = array(); $exif = array(); $folder = "./images/"; $insrt = 'INSERT INTO images VALUES (img_id, '; $file_name = ''; $file_location =''; $copyright =''; $caption = ''; $file_date = ''; $file_time = ''; $camera = ''; $speed = ''; $fNo = ''; $ISO = ''; /*================================= Open folder and read relevant files =================================*/ if ($handle = opendir('./images')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { $file_name = $file; //>>> File Name <<< $file_location = $folder . $file; //>>> File Location <<< $exif = exif_read_data($file_location, 'EXIF'); //>>> Read exif data <<< /*============================================================== Check if the 'Copyright' info existe in the exif data, and if it doesn't set the $copyright variable to the relevant value. ==============================================================*/ if (array_key_exists('Copyright', $exif)) { $copyright = $exif['Copyright']; } else { $copyright = "copy name"; } $caption = $exif['COMMENT'][0]; //>>> Get the Caption <<< //>>> Re-format DateTime into separate date and time var's $file_date & $file_time <<< $temp = substr($exif['DateTime'], 0, 10); $file_date = substr($temp, 8, 2) . substr($temp, 4, 4) . substr($temp, 0, 4); $file_time = substr($exif['DateTime'], 11, 8); //>>> Set the rest of the variables <<< $camera = $exif['Model']; //>>> Get the camera make and model <<< $speed = $exif['ExposureTime']; //>>> Get the shutter speed <<< $fNo = $exif['COMPUTED']['ApertureFNumber']; //>>> Get the f No. <<< $ISO = $exif['ISOSpeedRatings']; //>>> Get the ISO rating <<< //>>> Fill the $store[] array with the relevant bits for each seperate query <<< $store[] = $insrt . "'" . $file_name . "', " . "'" . $file_location . "', " . "'" . $copyright . "', " . "'" . $caption . "', " . "'" . $file_date . "', " . "'" . $file_time . "', " . "'" . $camera . "', " . "'" . $speed . "', " . "'" . $fNo . "', " . "'" . $ISO . "')"; } } closedir($handle); } /*============================================================================= Get individual queries from $store[] and INSERT INTO images the relevant VALUES =============================================================================*/ $num_queries = count($store); //>>> Check the number of queries in the array $store $loop = 0; //>>> Starting point for query No. bearing in mind that array keys are numbered from zero while ($loop <= $num_queries - 1) { $query = $store[$loop]; if (!mysql_query($query)){ die('Error: ' . mysql_error()); } mysql_query($query); $loop++; } ?> I know it's not pretty, but that can be attended to once working properly. I am quite sure that it will be a very simple solution, probably so simple that I haven't even thought of it. Similar TutorialsI've recently had a problem with my admin site where PHP sessions, which are stored in a MySQL database, are duplicating and causing the page to return to the login screen. Usually the site works fine in Firefox, but stops working in IE and Safari. This problem suddenly appeared over night with no change to the files. Due to the amount of code, I'm reluctant to post it all, but does anyone have a suggestion on why this could be happening and how to solve it? Hi
I am reading in data from a csv file
if (($handle = fopen("data.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { echo "User Name: $data[0]"; echo "Booking IDs: $data[1]"; } echo "<hr>";The problem is some of the usernames are duplicated so get outputted the same user name 20 times but with different IDs, obviously but I am unsure how to group them together. I can't seem to figure out how to write if the next username is the same as current then just add another ID not go through the entire loop. Any ideas? Thanks Hello there, I'm looking for a PHP method to duplicate a line, for example if I wanted to duplicate this line: mail($to,$subject,$message,$headers); How could I specify a value of how many are displayed instead of doing this to send it 3 times: mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); mail($to,$subject,$message,$headers); Many thanks <?php // Daniel URL duplicator. // Input links list. $linksList = "links.txt"; // How many times to duplicate the url? $manyTimes = 1000; // Read in the list. for ($x = 0; $x <= $manyTimes; $x++) { $handle = fopen($linksList, "r"); $line = fgets($handle); echo $line; fclose($handle); } ?>Hey Guys, I'm stuck on this simple bit of code lol what I'm trying to do is load in a list of urls: site1.com site2.com site3.com etc For each site that is read, I'm trying to duplicate it X times, above would print to screen the same url 1000 times, then move onto the next print it 1000 times etc until the list is done (or how ever many times I select) I can't think of the best way to do it! any help would be appreciated guys! Graham Hi I have this simple code $one = rand(1,9); $two = rand(1,9); $three = rand(1,9); but I need to change it so that they are all unique and the same number is not used more than once can anyone help? thanks Hi everyone, I don't know whether this is a PHP or MySql problem, but I think it is the former. The following code queries the database correctly, (and before you ask, there are no duplicate database entries), but the output duplicates every row. e.g., hammer (jpg image) hammer hammer (jpg image) hammer saw (jpg image) saw saw (jpg image) saw screwdriver (jpg image) screwdriver screwdriver (jpg image) screwdriver and so on. I cannot see why the code causes the row to repeat. Code: [Select] <?php session_start(); if (isset($_SESSION['id'])) { // Put stored session variables into local php variable $id = $_SESSION['id']; $userId = $_SESSION['userId']; $userGroup = $_SESSION['userGroup']; $managerId = $_SESSION['managerId']; } include_once("demo_conn.php"); $sql = mysql_query("SELECT * FROM users WHERE id='$id'"); while($row = mysql_fetch_array($sql)) { // Get member data into a session variable $egroup = $row["egroup"]; session_register('egroup'); $_SESSION['egroup'] = $egroup; } $query = mysql_query("SELECT topics.url_big, topics.url_small, topics.title, topics.$egroup, quiz.passState, quiz.userDate FROM topics INNER JOIN quiz ON (topics.managerId = quiz.managerId) WHERE topics.$egroup = 1 ORDER BY title ASC"); while ($row1 = mysql_fetch_array($query)) { echo "<a href='../../wood/wood_tool_images/{$row1['url_big']}' target='_blank'><img src='../../wood/wood_tool_images/{$row1['url_small']}' /><br />\n"; echo "{$row1['title']} <br />\n"; } ?> Please help and amend the code Save without repetition required $read[0] I hope that my example is clear to you I apologize for bothering you. I am not good in English <?php $fileLocation = getenv("DOCUMENT_ROOT") . "/rt.txt"; $file = fopen($fileLocation,"a"); $n1 = $_POST['n1']; $n2 = $_POST['n2']; for($i = 0; $i < count($file); $i++){ $read = explode("|", $file[$i]); if($n1 == $read[0]){ echo 'Repetition'; } else { fwrite($file,$n1.'|'.$n2."\r\n"); }
Can anyone tell me why this is not INSERTing? My array data is coming out just fine.. I've tried everything I can think of and cannot get anything to insert.. Ahhhh! <?php $query = "SELECT RegionID, City FROM geo_cities WHERE RegionID='135'"; $results = mysqli_query($cxn, $query); $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($row = mysqli_fetch_array($results)) { $insert_city_query = "INSERT INTO all_illinois SET state_id=$row[RegionID], city_name=$row[City] WHERE id = null" or mysqli_error(); $insert = mysqli_query($cxn, $insert_city_query); if (!$insert) { echo "INSERT is NOT working!"; exit(); } echo $row['City'] . "<br />"; echo "<pre>"; echo print_r($row); echo "</pre>"; } //while ($rows = mysqli_fetch_array($results)) } //if (mysqli_num_rows($results)) else { echo "No results to get!"; } ?> Here is my all_illinois INSERT table structu CREATE TABLE IF NOT EXISTS `all_illinois` ( `state_id` varchar(255) NOT NULL, `city_name` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; Here is my source table geo_cities structu CREATE TABLE IF NOT EXISTS `1` ( `CityId` varchar(255) NOT NULL, `CountryID` varchar(255) NOT NULL, `RegionID` varchar(255) NOT NULL, `City` varchar(255) NOT NULL, `Latitude` varchar(255) NOT NULL, `Longitude` varchar(255) NOT NULL, `TimeZone` varchar(255) NOT NULL, `DmaId` varchar(255) NOT NULL, `Code` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; I'm missing something here. I have a form, and when the submit is pressed, the relevant post data inserts into table one, then I want the last insert id to insert along with other form data into a second table. The first table's still inserting fine, but I can't get that second one to do anything. It leapfrogs over the query and doesn't give an error. EDIT: I forgot to add an error: I get: 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 'usage, why VALUES ('14', '', '123', '','1234', '', '')' at line 1 query:INSERT INTO tbl_donar (donar_fname, donar_name, donar_address, donar_address2, donar_city, donar_state, donar_zip, donar_email, donar_phone, donar_fax, donar_company) VALUES ('test 14', 'asdfa', 'asdf', 'adf','asdf', '', '', '', '123', '', '') Code: [Select] if (empty($errors)) { require_once ('dbconnectionfile.php'); $query = "INSERT INTO tbl_donar (donar_fname, donar_name, donar_address, donar_address2, donar_city, donar_state, donar_zip, donar_email, donar_phone, donar_fax, donar_company) VALUES ('$description12', '$sn', '$description4', '$cne','$description5', '$description6', '$description7', '$description8', '$description9', '$description10', '$description11')"; $result = @mysql_query ($query); if ($result) { $who_donated=mysql_insert_id(); $query2 = "INSERT INTO tbl_donation (donor_id, donor_expyear, donor_cvv, donor_cardtype, donor_authorization, amount, usage, why) VALUES ('$who_donated', '$donate2', '$donate3', '$donate4','$donate5', '$donate6', '$donate7')"; $result2 = @mysql_query ($query2); if ($result2) {echo "Info was added to both tables! yay!";} echo "table one filled. Table two was not."; echo $who_donated; //header ("Location: http://www.twigzy.com/add_plant.php?var1=$plant_id"); exit(); } else { echo 'system error. No donation added'; Hello, I'm having a bit of a problem here, all help to this issues would be much appreciated I am trying to use text boxes to insert numbers into the database based on what is inputed. If I have a string, like this for example: $variable = 09385493; And I want to insert it into the database like this: mysql_query("INSERT INTO integers(number) VALUES ('$variable')"); When checking the integers table in my database, looking at the number field, the $variable that was inserted is outputted as 9385493 Notice the number zero was taken out of the front of the number. If the number is double 0's (009385493), both of those zero's would disappear, too. Thanks I'm trying to use PDO and get used to doing things this way. I've been away from php/mysql for a few years, so, I'm crusty. I'm not getting any error messages back on this code, but the insert just doesn't happen. My first guess is that I'm doing something wrong with the datetime now() function. But, I may not have the PDO code right. I tried the script the old fashion way with mysql_query() and that worked. So, it has to be something in this code. I believe my server is set up to do PDO as it shows: PDO PDO support enabled PDO drivers mysql, sqlite pdo_mysql PDO Driver for MySQL, client library version 5.0.45 My php version is 5.2.14 and Mysql is 5.0.45. Any help would be appreciated. Code: [Select] $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $sql=$DBH->prepare("INSERT INTO assets(asset_name,date_added,short_desc) VALUES (:asset_name,NOW(),:short_desc)"); $sql->bindParam(':asset_name',$asset_name); $sql->bindParam(':short_desc',$short_desc); $name=$_POST["input1"]; $short_desc=$_POST["input2"]; $DBH->exec(); echo $name; echo "\nPDO::errorInfo():\n"; print_r($DBH->errorInfo()); } catch(PDOException $e) { echo "Syntax Error: ".$e->getMessage(); } hi; Code: [Select] $giden = $_GET['sehir_part']+1; $url = '31.php?sehir_part='.$giden.''; //$erkek_top = 7 for($q=1;$q<=7;$q++) { //i want insert into to mysql in here ; but its doing only one inserting so i want be 7 more insert } header( 'refresh:1;url=31.php?sehir_part='.$giden)and in every page loading i want inserting to mysql againg pls helpme thanks I am working with a insert query... Code: [Select] $query="INSERT INTO user_info_more (website) VALUES ('".$website."') WHERE id='$_SESSION[id]'"; mysql_query($query) or die ('Unable to register an account with following details 1'); but the output is " Unable to register an account with following details 1" Basically i have a row with 6 cloumns in mysql database in which only the id column and name column is filled... Now i want to insert $website in the "website" column of the database... Neither i can update as the website column initially is null... I do not know what to do.... A lot of cnfusion I get the following message: Quote name4Query failed: Unknown column 'late' in 'field list' with this code. What does it mean? Code: [Select] <?php $apt=$_POST['search_term']; $stat = mysql_connect("localhost","root",""); $stat = mysql_select_db("prerentdb"); $query = "SELECT name FROM payments WHERE late = 'L'"; $stat = @mysql_fetch_assoc(mysql_query($query)); echo $stat["name"]; $name=$_POST['name']; $apt=$_POST['apt']; $amtpaid=$_POST['amtpaid']; $rentdue=$_POST['rentdue']; $prevbal=$_POST['prevbal']; $hudpay=$_POST['hudpay']; $tentpay=$_POST['tentpay']; $datepaid=$_POST['datepaid']; $late=$_POST['late']; $comments=$_POST['comments']; $paidsum=$_POST['paidsum']; $query = " INSERT INTO payhist (name,apt,amtpaid,rentdue,prevbal, hudpay,tentpay,datepaid,late,comments,paidsum) VALUES('$name','$apt','$amtpaid','$rentdue','$prevbal', '$hudpay','$tentpay','$datepaid','$late','$comments','$paidsum')"; $stat = mysql_query($query) or die('Query failed: ' . mysql_error()); mysql_close(); echo "data inserted<br /><br />"; ?> i need the insert code Would someone be able to tell me why I can't run a successful mysql_query($sql) with $sql="INSERT INTO myDB.Titles (Title, Year, cID) values('". $title . "', '" . $year . "', '" . $cID . "')"; $sql echoes out to "INSERT INTO myDB.Titles (Title, Year, cID) values('Test', '2000', '2')" It looks right but I'm probably off on the quotes somewhere. Thanks in advance. Just a quick question I have a form, couple of drop down boxes, input fields etc.. at the end is the submit button. now my question is should my insert into database sqls go before the submit button inside the form? out side the form? after the button inside the form? If by any chance you could give me some advice on the best way to layout my sql that would be great. They are big and go into three tables, at the moment I have them as three seperate queries but I think they must be able to go into one. can someone please help me with the layout and syntax. here is what the queries look like at the moment: if ($IBselect=$_POST ['IBselect']); { //CUSTOMER $enterCust="INSERT INTO customer(username, password, title, firstName, lastName, address, town, country, postCode, phone, email, dateCust) VALUES ('$_POST[username]', '$_POST[password]', '$_POST[title]', '$_POST[firstName]', '$_POST[lastName]', '$_POST[address]', '$_POST[town]', '$_POST[country]', '$_POST[postCode]', '$_POST[phone]', '$_POST[email]', 'DATE: Auto CURDATE()', CURDATE()"; $enterCust_query=mysql_query($enterCust)or die(mysql_error()); //CARD $enterCard="INSERT INTO card(cardNumber, name, expDate, cardID) VALUES ('$_POST[cardNumber]','$_POST[name]', ' $_POST[expDate]', '$_POST[cardID]')"; $enterCard_query=mysql_query($enterCard); //BOOKING $RCenterBook=mysql_query("INSERT INTO booking (custNumber, cardID, rideName, seatNo1, seatNo2, price, price2, dateBook, ID_time_tbl) VALUES ('$custNumber', '$_POST[cardID]', '$rideName', '$_SESSION[IBextract]', '$_SESSION[IBextract2]', '$IBendPrice1', '$IBendPrice2', 'DATE: Auto CURDATE()', CURDATE()', '$_SESSION[IB_slot_Time]'"); $IBenterBooking_query=mysql_query($IBenterBook); if (!mysql_query($enterCard, $enterCust, $IBenterBook)) { die("Error:" .mysql_error()); } echo "1 record added IB"; } Thanks =) Okay, I'm hoping one of you can help me. I have a mysql database that I have configured through phpmyadmin. I have an android app that simply makes and sends a mysql query I can get it to successfully return values when using Select statements but when I use INSERT INTO, it returns " Error Query is invalid" BUT BUT BUT, when I use the same string and enter it through the sql tab in myphpadmin it works fine ! So here is the string ( the semicolons at the end of each field name are so I can use something common to split the string up when the data arrives back on the phone) Code: [Select] randomkey||||||INSERT INTO table4 (`geolat;` , `geolong;` , `mode;` , `destgeolat;` , `destgeolong;` , `cellphone;` , `email;` , `carrego;` , `colour;` , `rating;` , `comment;`) VALUES (0.0,0.0,'driver' ,-43.54779,172.62472, , '' ,'' , 'text' , 'ratingleftblank' , 'commentblank' ) the index4.php script is as follows Code: [Select] ?php /* * Written By: * James */ /************************************CONFIG****************************************/ //DATABSE DETAILS// $DB_ADDRESS="mysql1.openhost.net.nz"; $DB_USER="bling44"; $DB_PASS="sadlyinept"; $DB_NAME="bling44"; //SETTINGS// //This code is something you set in the APP so random people cant use it. $SQLKEY="randomkey"; /************************************CONFIG****************************************/ //these are just in case setting headers forcing it to always expire and the content type to JSON header('Cache-Control: no-cache, must-revalidate'); header('Content-type: application/json'); if(isset($_POST['tag'])){ //checks ifthe tag post is there $tag=$_POST['tag']; $data=explode("||||||",$tag); //split the SQL statement from the SQLKEY if($data[0]==$SQLKEY){ ///validate the SQL key $query=$data[1]; $link = mysql_connect($DB_ADDRESS,$DB_USER,$DB_PASS); //connect ot the MYSQL database mysql_select_db($DB_NAME,$link); //connect to the right DB if($link){ $result=mysql_query($query); //runs the posted query (NO PROTECTION FROM INJECTION HERE) if($result){ if (strlen(stristr($query,"SELECT"))>0) { //tests if its a select statemnet $outputdata=array(); while ($row = mysql_fetch_assoc($result)){ $outputdata[]=$row; //formats the result set to a valid array } echo json_encode(array("VALUE",$tag,array_merge($outputdata))); //sends out a JSON result with merged output data } else { echo json_encode(array("VALUE",$tag,array_merge(array(array("AFFECTED_ROWS ".mysql_affected_rows($link)))))); //if the query is anything but a SELECT it will return the array event count } } else echo json_encode(array("VALUE",$tag,array_merge(array(array("ERROR QUERY IS INVALID"))))); //errors if the query is bad mysql_close($link); //close the DB } else echo json_encode(array("VALUE",$tag,array_merge(array(array("ERROR Database Connection Failed"))))); //reports a DB connection failure } else { echo json_encode(array("VALUE",$tag,array_merge(array(array("ERROR BAD CODE SUPPLIED"))))); //reports if the code is bad } } ?> So to reiterate. I can search the DB but can't INSERT INTO, unless I go through the myphpadmin interface. Any ideas are very much appreciated I am wondering about the following problem: I have two sessions, one for the user ($_SESSION['user_id']) and second one for the products inside cart ($_SESSION['cart']). I need to insert data into table racun. I did it this way and it works, but i want to know if this can be done better? Code: [Select] while ($row=mysql_fetch_array($query)){ $id = $_SESSION['korisnik_id']; $idp = $row['product_id']; $kol = $_SESSION['cart'][$row['product_id']]['quantity'] ."<br>"; $insert = "INSERT INTO racun (product_id, quantity, korisnik_id) VALUES ('$idp', '$kol', '$id') "; $result = mysql_query($insert); } hey developers,
i have problem to get last insert id. btw.. i try to put that code on my mvc creation.
on register_model page i write like this:
public function numbering(){ $sth = $this->db->prepare('SELECT * FROM member_data'); $result = $this->db->lastInsertId(); return $result; } and for the controllers page, i write the code like this: $c = $this->model->numbering(); foreach ($c as $key => $value) { $data = $result('id'); } $abc['member_id'] = $data; but i didn't get the results,.. can you help me? |