PHP - Updating Issue
HI there im having a problem with updating one table with anopther tables contents atm i have this code:
Code: [Select] if($sql) { $msg = "Taxi Accepted sucessfully."; mysql_query("INSERT INTO user_location ( User_ID,User_Longitude,User_Latitude) SELECT User_ID,User_Longitude,User_Latitude FROM quotes") or die (mysql_error()); } else { $msg = "Taxi not Accepted sucssfully try again."; echo "$msg"; } The error message im getting is :Duplicate entry '1' for key 1 :S any help at all Thank You Similar TutorialsThe below code is taking the submission from the form and inserting into the members table, but it is not updating the application table. if($_GET['view']=="applications"){ $section.=' - New Investor Applications'; $content=' <div class="main"> <div class="main_header">New Investor Applications</div>'; if($_GET['approved']=="update"){ $id=(int)$_GET['id']; $approved=$_POST['approved']; $approved=sanitize($approved); $username=$_POST['username']; $username=sanitize($username); $password=$_POST['password']; $password=kam3($password); $approved_sql="INSERT INTO members (username, password, application_id) VALUES ('$username', '$password', '$id')"; $approved_result=mysql_query($approved_sql) or die(mysql_error()); $approved_rows=mysql_affected_rows(); $update_approved_sql='UPDATE application SET approved="y" WHERE id="$id"'; $update_approved_result=mysql_query($update_approved_sql) or die(mysql_error()); $update_approved_rows=mysql_affected_rows(); if($approved_rows==1 && $update_approved_rows==1){ header("Location: ./index.php??admincp=investors&view=applications&approved=updated"); } } elseif($_GET['approved']=="updated"){ $content.='<div class="center"> Application Status Updated. <br /> <a href="http://www.makethemoviehappen.com/index.php?admincp=investors&view=accounts">View Investor Accounts</a> </div>'; } elseif(isset($_GET['id'])){ $id=(int)$_GET['id']; $member_list_query="SELECT * FROM application WHERE id='$id'"; $member_list_result=mysql_query($member_list_query); while($member_list_row=mysql_fetch_array($member_list_result)){ extract($member_list_row); } $section.=' - '.$name.' - Application #'.$id.''; $content.=' <div class="center bold eighteen">Investor Application - '.$name.' - #'.$id.'</div> <br /> <div class="investor_applications_wrapper"> <div class="title_data_row"> <div class="title"><div class="investor_padding">Name:</div></div> <div class="data"><div class="investor_padding">'.$name.'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">Organization (if applicable):</div></div> <div class="data"><div class="investor_padding">'.$organization.'</div></div> </div> <div class="title_data_row"> <div class="title" class="title"><div class="investor_padding">E-Mail Address:</div></div> <div class="data"><div class="investor_padding">'.$email.'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">Phone Number:</div></div> <div class="data"><div class="investor_padding">'.$phone.'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">Brief description of the organization you represent (if applicable):</div></div> <div class="data"><div class="investor_padding">'.$company_description.'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">Nature of your inquiry into Make the Movie Happen:</div></div> <div class="data"><div class="investor_padding">'.$nature_inquiry.'</div></div> </div> <div class="title_data_row accredited_spacer"> <div class="bold center eighteen">"Accredited Investor" Qualification</div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">The applicant is an entity with total assets in excess of $5,000,000:</div></div> <div class="data"><div class="investor_padding">'.ucfirst($company_assets).'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">The applicant is a natural person whose individual net worth is above $1,000,000 or annual income of $2/300,000:</div></div> <div class="data"><div class="investor_padding">'.ucfirst($natural_person).'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">The applicant is an employee benefit plan within the meaning of Title I of ERISA:</div></div> <div class="data"><div class="investor_padding">'.ucfirst($employee_benefit_plan).'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">The applicant is licensed, or subject to supervision, by U.S. federal or state examining authorities as a bank or savings and loan association, insurance company or licensed small business investment company:</div></div> <div class="data"><div class="investor_padding">'.ucfirst($bank_savings).'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">The applicant is registered with the U.S. Securities and Exchange Commission (the "SEC") as a broker or dealer under the Securities Exchange Act of 1934 or qualifies as a "business development company":</div></div> <div class="data"><div class="investor_padding">'.ucfirst($broker_dealer).'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">The applicant is a private business development company as defined in Section 202(a)(22) of the Investment Advisers Act of 1940, as amended:</div></div> <div class="data"><div class="investor_padding">'.ucfirst($development_company).'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">The applicant is an entity in which all of the equity owners are persons described above (including an IRA where the participant is an accredited investor):</div></div> <div class="data"><div class="investor_padding">'.ucfirst($equity_owners).'</div></div> </div> <div class="title_data_row"> <div class="title"><div class="investor_padding">Agreement Confirmed</div></div> <div class="data"><div class="investor_padding">'.ucfirst($confirm_agreement).'</div></div> </div> </div> <div class="investors_approve_form"> <div class="center bold eighteen">Approve Application</div> <form action="./index.php?admincp=investors&view=applications&approved=update&id='.$id.'" method="post"> <p><label>Username: </label><input type="text" name="username" size="32" /></p> <p><label>Password: </label><input type="text" name="password" size="32" /></p> <p><label>Approve: </label> Yes <input type="radio" name="rating" value="y" /> No <input type="radio" name="rating" value="n" /></p> <input type="submit" name="go" value="Go" /> </form> </div> <div class="spacer_bottom"> </div> '; } else{ $new_applications="SELECT * FROM application WHERE approved='n'"; $new_applications_result=mysql_query($new_applications); while($new_applications_row=mysql_fetch_assoc($new_applications_result)){ extract($new_applications_row); $content.='<div class="center"><a href="./index.php?admincp=investors&view=applications&id='.$id.'">'.(!empty($username) ? ''.$username.'' : ''.$name.'').'</a></div>'; } } $content.='</div>'; } Hi, I'm using php to access the mysql database using mysqli and I have a field on my table called "timestamp" and it's set as a timestamp and has current_time (I think in phpmyadmin it was a tick option so I clicked it) and when I update that row in my table the field "timestamp" doesn't update with the timestamp from when it was last updated/modified. I thought the field option timestamp automatically did that? I'm guessing not.. is there a way I can update the timestamp with the current time in my query? $query1 = "select * from movies where title = '".$title."' ;"; $result1 = mysql_query($query1) or die('Could Not Execute The Query'); while ($row = mysql_fetch_assoc($result1) ) { for($f=0; $f<$parts[$current_k]; $f++ ) { touch("$base_folder/{$hos}/".$linking[$sum].".php"); $old_part_href = $row['href_parts']; $updated_part = $old_part_href.$new; $query_href = 'update movies set href_parts = \''.$updated_part.'\''; mysql_query($query_href) or die('COULD NOT EXECUTE THE QUERY FOR PARTS HREF'); $new = "{$base_folder}/{$hos}/".$linking[$sum].".php"; $sum++; } } what i am trying to do is take the value of href_parts and add the new href of the page to the existing value on the href_parts and update the href_parts field in my db.. but i am not getting the desired results.. all i am getting in the db is the last value that is passed in the loop in the db.. i want to save the values which are exisiting in the db and add the newly created values to itt.. can anyone help please.. I'm back, I have a code that based on my understanding should work, but needless to say doesn't <?php $sql ="select * from `piprice`"; $result = mysql_query($sql); $count = mysql_num_rows($result); echo "<table border=1><tr><td>Product Name</td><td>Item ID</td><td>Price</td><td>Enabled</td>"; echo "<form action=main.php?id=test1.php method=post>"; while ($row = mysql_fetch_array($result)) { echo "<tr><td>".$row['product name']."</td>"; echo "<td>".$id[] = $row['item id'];$row['item id']."</td>"; echo "<td>".$row['price']."</td>"; $enabled[] = $row['enabled']; echo"<td><select name=".$enabled.">< <option Value=".$row['enabled'].">".$row['enabled']."</option> <option Value=Yes>Yes</option> <option Value=No>No</option> /select></td</tr>"; } echo "<input name=submit type=submit value=Update>"; echo "</form></table>"; if(isset($_POST['submit'])) { for($i=0;$i<$count;$i++){ $sql1="UPDATE `piprice` SET `enabled` = '$enabled[$i]' WHERE `item id` ='$id[$i]'"; $result1=mysql_query($sql1) or die (mysql_error()); } } ?> Basically I want to be able to pick yes/no and have it update in the database. One a side note is there a good site for me to learn php on (I just know the basics) besides asking 101 questions here $sqld = "SELECT * FROM orders WHERE `id`='$delete' AND `name`='$inf2[name]' AND `email`='$inf2[email]' LIMIT 1"; $csql = $db->query($sqld); $ccheck = $csql->fetch(PDO::FETCH_NUM); $cinf = $csql->fetch(PDO::FETCH_ASSOC); $quantity = $cinf[quantity]; $code = $cinf[code]; $stmt11 = $db->prepare('UPDATE feeds SET quantity=quantity-:quantity WHERE code=:code'); $stmt11->bindValue(':quantity', $quantity, PDO::PARAM_STR); $stmt11->bindValue(':code', $code, PDO::PARAM_STR); $stmt11->execute(); $id = $delete; $name = $inf2[name]; $stmt2 = $db->prepare("DELETE FROM orders WHERE id=:id AND name=:name"); $stmt2->bindValue(':id', $id, PDO::PARAM_STR); $stmt2->bindValue(':name', $name, PDO::PARAM_STR); $stmt2->execute();OK, i have just been told i should start using PDO instead of mysql to update my tables. This code works to delete the order but doesn't update the feeds section. All this is new to me so far and i think i am getting the hang of it. Should i still be using the quantity=quantity-:quantity or is there another way to do it with PDO? Sorry, i posted this in the wrong forum. Hope someone here can help until it's moved Edited by Self_Taught_Still_Learning, 30 May 2014 - 03:30 PM. So, I am making a CMS for my school and I am having some trouble. It's a magazine sort of CMS and what I want is that when you click on a certain thing it continues onto the next page. Through the CMS you can create pages - when you do this each page gets a unique PID. To access the pages you have to enter the PID on the end of the URL, e.g. : http://www.myschool.com/magazine/index.php?pid=x. What I need is a code that when an image gets clicked the PID number in the URL goes up by one. Thanks Okay, I have a useredit page in where a user can manage their account info. All the text field and SQL connections work fine, and they all update perfectly. But when I go ahead and add my own text field (first name) and hit submit, it says success - but in my SQL it hasn't actually updated ... What the Ef? Here are my snippets of my codes: --useredit.php-- <form action="process.php" method="POST"> <input type"text" name"firstname" value="<? if($form->value("firstname") == ""){ echo $session->userinfo['firstname']; }else{ echo $form->value("firstname"); } ?>"> <input type="hidden" name="subedit" value="1"> <input type="submit" value="Edit Account"> --process.php-- function procEditAccount(){ global $session, $form; /* Account edit attempt */ $retval = $session->editAccount($_POST['curpass'], $_POST['newpass'], $_POST['email'], $_POST['firstname']); /* Account edit successful */ if($retval){ $_SESSION['useredit'] = true; header("Location: ".$session->referrer); } --session.php-- function editAccount($subcurpass, $subnewpass, $subemail, $subfirstname){ global $database, $form; if($subfirstname){ $database->updateUserField($this->username,"firstname",$subfirstname); } --database.php-- function updateUserField($username, $field, $value){ $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'"; return mysql_query($q, $this->connection); } If you need to see more code, let me know. Would appreciate the help, thanks! Ollie! Hey, im trying to fix a line of code that should update a field in the database when filled in. The code i think handles this is below. <input type="text" id="uuser_address" name="uuser_address" value="<?php echo("$slide[address]"); ?>"><br /><input type="text" id="uuser_town" name="uuser_town" value="<?php echo("$slide[town]"); ?>"><br /><input type="text" id="uuser_county" name="uuser_county" value="<?php echo("$slide[county]"); ?>"><br /><input type="text" id="uuser_postcode" name="uuser_postcode" value="<?php echo("$slide[postcode]"); ?>"></div> can anyone tell me why this is updating all the address fields other than the postcode? thanks, gavin Hi friends, the below code, which I've worked on quite a while, creates a dropdown, selects a record with a link to visit the url of that record. one ? can I update the table b4 closing? -------------------------------------------------- below is code: <?php include ('homedb-connect.php'); ?> <!DOCTYPE><html><head> <title>lookup menu</title> </head> <body><center><b> <form name="form" method="post" action="">
<?php //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">' . '--- Select account ---' . '</option>'; $query = mysqli_query($conn, "SELECT target FROM infotbl"); if ($query === false) { echo "Something went wrong<br />"; echo mysqli_error($conn); } else { while ($row = mysqli_fetch_array($query)) { echo "<option value='" . $row['target'] . "'>" . $row['target'] . '</option>'; } } echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/> </form><center>
<?php // ============================================== if (isset($_REQUEST['target'])) { $target = $_REQUEST['target']; // =============================================== $fetch = "SELECT id, target, purpose, user, password, email, visits, lastused FROM infotbl WHERE target = '" . mysqli_real_escape_string($conn, $target) . "'"; // ===============================================================================
$result = mysqli_query($conn, $fetch); if (!$result) { echo "Error:" . (mysqli_error($conn)); }
//display the table echo '<table border="1"><tr><td bgcolor="cyan" align="center">lookup menu</td></tr> <tr><td> <table border="1"> <tr> <td>id</td> <td bgcolor="#ccffff"> Target </td> <td bgcolor="violet"> Purpose </td> <td bgcolor="#ccffff"> User </td> <td bgcolor="#ccffff">Password </td> <td bgcolor="#ccffff"> Email </td> <td bgcolor="#cyan"> Visits </td> <td bgcolor="#cyan"> lastused</td> </tr>';
while ($data = mysqli_fetch_row($result)) {
// ========================================================== $url = "http://$target"; $link = '<a href="' . $url . '">' . $data[0] . '</a>'; // ===========================================================
echo ("<tr><td> $link </td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td> <td>$data[4]</td><td>$data[5]</td><td>$data[6]</td><td>$data[7]</td></tr>"); } echo '</table> </td></tr></table>'; } ?> </body></html> ------------------------------------------------------ this is my update code: <?php $target = $_POST["target"]; $visits = 'visits'; $Lastused = 'Lastused'; $sql = "UPDATE receiptno SET visits=visits+1, lastused=NOW() WHERE target=$target"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close(); ?> Hi there im going a little bit mad now.... i spent a while trying to work out why my form didnt update or redirect... After head scratching i remade a test form... That also doesnt update or redirect?? I must be missing something here?? So basically when the user clicks submit nothing happens, why?? Code: [Select] <?php require_once('Connections/swb.php'); ?> <?php session_start(); if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) { $updateSQL = sprintf("UPDATE player SET `Day`=%s WHERE PlayerName=%s", GetSQLValueString($_POST['days'], "int"), GetSQLValueString($_POST['playername'], "text")); mysql_select_db($database_swb, $swb); $Result1 = mysql_query($updateSQL, $swb) or die(mysql_error()); $updateGoTo = "logout.php"; if (isset($_SERVER['QUERY_STRING'])) { $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?"; $updateGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $updateGoTo)); } ?> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> <form action="<?php echo $editFormAction; ?>" id="form1" name="form1" method="POST"> <input type="button" value="End Turn" /> <input name="days" type="hidden" id="days" value="1"/> <input name="playername" type="hidden" id="playername" value="<?php echo $_SESSION['MM_Username']; ?>"> <input type="hidden" name="MM_update" value="form1"> </form> </body> </html> Thanks Sorry maybe a stupid question but Ive made a cron and its not updating the players cash as it should, can anyone spot why? I've looked but just cannot see it, Thanks appreciate your time for looking. Code: [Select] <?php include("server.php"); $sql = "SELECT * FROM players"; $que = mysql_query($sql); while($res=mysql_fetch_array($que)) { $sql2 = "SELECT * FROM players WHERE id = '$res[id]'"; $que2 = mysql_query($sql2) or die(mysql_error()); $res2 = mysql_fetch_array($que2); $hoes = $res2['Hoes']; $hobedding = $res2['MaxHoes']; $incomemod = $res2['HoIncome']; $morale = $res2['HoesMorale']; if ($hoes < $hobedding) { $income = (250 * $hoes * $incomemod * $morale); } else { if ($hoes > $hobedding) { $income = (250 * $hobedding * $incomemod * $morale) + (125 * ($hoes - $hobedding) * $incomemod * $morale); } $sql5 = "UPDATE players SET cash = cash + '$income' WHERE id = '$res[id]'"; mysql_query($sql5) or die(mysql_error()); } } ?> again my tables are movies| ID(PK) - Titles - Category(FK) - URL 0 Name 1 www.xyz.com categories| ID(PK) - Category 1 Comedy say i create a query SELECT * FROM movies WHERE Category="1" and it gave me all the movies from my table that is in the comedy category which should look like this: ID - Title - Category - URL 0 Name Comedy www.xyz 1 xyz Comedy www.abc etc.. How can i add a drop down menu beside each movie listed in that result that would let me change the category for it and save it ? like this, ID - Title - Category - URL 0 Name Comedy www.xyz [Dropdown] 1 xyz Comedy www.abc [Dropdown] [Save Button] being a newbie im going to guess that i will need a INSERT in here somewhere and not really sure how i would write my result echos. i have been trying all kinds of "update records" forms and cant get them right so i figured it may be easier to just try and create my own. if i could get some example or if you have more simple suggestions do you see anything wrong with this update code? i am having trouble setting the acntStatus=1. Code: [Select] <?php mysql_select_db($database_uploader, $uploader); $query = "SELECT * FROM members WHERE uname='$_SESSION[user]'"; $result = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result) or die(mysql_error()); $usedSpace = $row['bandwhitch']; $acntType = $row['acntType']; if ($acntType == 1) { $totalSpace = 500; } else { $totalSpace = 250; } if($usedSpace > $totalSpace) { echo "There is something wrong with your account. Please contact us!"; $usageError = true; mysql_query(sprintf("UPDATE members SET acntStatus='%s' WHERE uname='%d'", mysql_real_escape_string(1), $_SESSION['user'])) or die(mysql_error()); mysql_close($con); } $usagePercent = (round(($usedSpace/$totalSpace), 2)) * 100; // Convert to percentage } ?> I am trying to update a tiny int i have the if statement which says when tiny int is 1 echo closed and when tiny int 0 echo open. The problem is i am trying to query the result in a drop down but the option of status Closed doesnt appear. Code: [Select] <?php //connect to database $con=mysql_connect("localhost","root","15AE@ea27") or die("couldn't connect to mysql"); //select database $db=mysql_select_db("ac_res",$con) or die("database not found"); //get ID to Edit $id = $_GET['id']; //Query Fields to edit $sql = 'SELECT * FROM `ac_reservation` WHERE `id` = "'.$id.'"'; $query = mysql_query($sql) or die("Couldn't execute query. ". mysql_error()); $results = mysql_fetch_array($query); $status = 'status'; //Query the waiter table $waiter=mysql_query("SELECT fname FROM waiter") or die("query error"); ?> <form id="edituser" name="edituser" method="post" action="editresexec.php"> <table width="300" border="0" align="center" cellpadding="2" cellspacing="0"> <tr> <th> </th> <td><input name="id" type="hidden" class="textfield" value= <?php echo $results[id]?> /> </td> </tr> <tr> <th>First Name </th> <td><input name="fl_name" id="keyboard2" type="text" class="textfield" value= <?php echo $results[fl_name]?> /> </td> </tr> <tr> <th>Number of People</th> <td><input name="n_people" id="keyboard3" type="text" class="textfield" value= <?php echo $results[n_people]?> /> </td> </tr> <tr> <th>Table Number</th> <td><input id="t_number"name="t_number" type="text" class="textfield" value= <?php echo $results[t_number]?> /></td> </tr> <tr> <th>Waiter</th> <td><?php echo "<select name=waiter>"; while($r=mysql_fetch_array($waiter)) { //echo waiter name echo "<option value='".$r['fname']."'>".$r['fname']."</option>"; } echo "</select>"; ?> </td> </tr> <tr> <th>Status</th> <td><?php //If statement if($rows['status'] == 1) { $status = "Close"; } else $status = "Open"; //Drop Down Menu For Status echo "<select>"; echo "<option value='".$status."'>".$status."</option>"; echo "</select>"; ?> </td> </tr> <tr> <td> </td> <td><input type="submit" name="Update" value="Update" /></td> </tr> </table> </form> I'm just trying to get suggestions on what people think would be the best way to go with this. With the bottom part of this card where it s tarts working with the foreach loop its taking what was a UL and for each of each LI's and updating a table with its new data however this way isn't going to work as this is editing a user. Because there could be 5 in the database but the new edit user has only 4 lis so I'm sure you could all see the issue here. What I'm thinking would be best is to have it DELETE the existing characterIDs that have WHERE handler_ID = $handlerID and then just do a new INSERT statement. Anyone else think this would be the best way to go about this? Code: [Select] if (mysqli_num_rows($Qresult) == 0) { $query = "UPDATE `handlers` SET `userName` = '".$userName."', `password`='".$password."', `firstName`='".$firstName."', `lastName`='".$lastName."', `statusID`='".$statusID."', `isAdmin`='".$admin."', `defaultCharID`='".$defaultCharID."', `email`='".$email."' WHERE `ID` = '".$handlerID."'"; mysqli_query($dbc, $query); foreach ($characterIDs as $cID) { $query2 = "UPDATE `handler_characters` SET `handler_id` = '".$handlerID."', `characterID` = '".$cID."'"; mysqli_query($dbc, $query2); } $result = "good"; } Hi, I'm a beginner at PHP and am I'm trying to update an array but cant get it to work: This is my 'rates' page, There are 6 boxes that are the headings, and 6 boxes per line below for the data, I can get the headings to save but not the data lines below: rates-edit.php Code: [Select] <?php error_reporting(E_ALL); ini_set('display_errors', 2); // Include the necessary files include_once '../inc/db.inc.php'; // Open a database connection $db = new PDO(DB_INFO, DB_USER, DB_PASS); // Extract details from database $sql = "SELECT title1, title2, title3, title4, title5, title6 FROM rates WHERE id=1"; $stmt = $db->prepare($sql); $stmt->execute(); $e = $stmt->fetch(); $sql2 = "SELECT 1, 2, 3, 4, 5, 6 FROM ratestable ORDER BY id ASC"; $stmt2 = $db->prepare($sql2); $stmt2->execute(); $e2 = $stmt->fetch(); ?> <!DOCTYPE html> <html lang="en"> <head> <h3>Rates Table</h3> <form method="post" action="rates-editupdate.php" enctype="multipart/form-data"> <input type="text" name="title1" maxlength="10" value="<?php echo $e['title1'] ?>" class="rates" /> <input type="text" name="title2" maxlength="10" value="<?php echo $e['title1'] ?>" class="rates" /> <input type="text" name="title3" maxlength="10" value="<?php echo $e['title3'] ?>" class="rates" /> <input type="text" name="title4" maxlength="10" value="<?php echo $e['title4'] ?>" class="rates" /> <input type="text" name="title5" maxlength="10" value="<?php echo $e['title5'] ?>" class="rates" /> <input type="text" name="title6" maxlength="10" value="<?php echo $e['title6'] ?>" class="rates" /> <?php while($e2 = $stmt2->fetch()) { ?> <input type="text" name="1" maxlength="10" value="<?php echo $e2['1'] ?>" class="rates" /> <input type="text" name="2" maxlength="10" value="<?php echo $e2['2'] ?>" class="rates" /> <input type="text" name="3" maxlength="10" value="<?php echo $e2['3'] ?>" class="rates" /> <input type="text" name="4" maxlength="10" value="<?php echo $e2['4'] ?>" class="rates" /> <input type="text" name="5" maxlength="10" value="<?php echo $e2['5'] ?>" class="rates" /> <input type="text" name="6" maxlength="10" value="<?php echo $e2['6'] ?>" class="rates" /> <?php } ?> <input id="button-upload" class="button" type="submit" name="submit" value="Save Changes" /> <input id="button-upload" class="button" type="submit" name="submit" value="Add New Row" /> </form> </body> </html> This is the page that updates the database, I cant get the loop/foreach to work... rates-editupdate.php Code: [Select] <?php error_reporting(E_ALL); ini_set('display_errors', 2); // Include the necessary files include_once '../inc/db.inc.php'; // Open a database connection $db = new PDO(DB_INFO, DB_USER, DB_PASS); // Check if coming from a POST command and Save Changes // THIS BIT WORKS :) if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['submit']=='Save Changes') { $sql = "UPDATE rates SET title1=?, title2=?, title3=?, title4=?, title5=?, title6=? WHERE id=1 LIMIT 1"; $stmt = $db->prepare($sql); $stmt->execute( array( $_POST['title1'], $_POST['title2'], $_POST['title3'], $_POST['title4'], $_POST['title5'], $_POST['title6'] ) ); $stmt->closeCursor(); // // THIS IS THE BIT THAT DOES NOT UPDATE: // $sql = "UPDATE ratestable SET 1=?, 2=?, 3=?, 4=?, 5=?, 6=? WHERE id=?"; $stmt = $db->prepare($sql); if(count($_POST['1']) > 0) { foreach($_POST AS $key => $val) { $stmt->execute(array( ($key), ($_POST['2'][$key]), ($_POST['3'][$key]), ($_POST['4'][$key]), ($_POST['5'][$key]), ($_POST['6'][$key]), ($val) ) ); } $stmt->closeCursor(); } // once updated return to rates page header('Location: rates-edit.php?success=1'); exit; } ?> thanks in advance Hello, I have been staring at my screen for the last couple of days and have finally run out of solutions. I have the code below where the data is generated form another page. The correct data is displayed but for some reason when I try to alter any data it does not work. I simply get the message, "Your profile has been successfully updated..." but nothing has been changed in the database. I think the code is not connecting to the correct table in the database.. I fail to see why this would be. Any help greatly appreciated. Code: [Select] <?php error_reporting(E_ALL); session_start(); ?> <?php require_once('appvars.php'); require_once('connectvars1.php'); // Connect to the database $dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name); if (!isset($_GET['user_id'])) { $query = "SELECT * FROM antique WHERE user_id = '" . $_SESSION['user_id'] . "'"; } else { $query = "SELECT * FROM antique WHERE user_id = '" . $_GET['user_id'] . "'"; } $data = mysqli_query($dbc, $query); if (mysqli_num_rows($data) == 1) { $row = mysqli_fetch_array($data); } ?> <?php require_once('appvars.php'); require_once('connectvars1.php'); // Make sure the user is logged in before going any further. if (!isset($_SESSION['user_id'])) { echo '<p class="login">Please <a href="login1.php">log in</a> to access this page.</p>'; exit(); } // Connect to the database $dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name); if (isset($_POST['submit'])) { // Grab the profile data from the POST $name = mysqli_real_escape_string($dbc, trim($_POST['name'])); $phone = mysqli_real_escape_string($dbc, trim($_POST['phone'])); $address1 = mysqli_real_escape_string($dbc, trim($_POST['address1'])); $address2 = mysqli_real_escape_string($dbc, trim($_POST['address2'])); $postcode = mysqli_real_escape_string($dbc, trim($_POST['postcode'])); $webadd = mysqli_real_escape_string($dbc, trim($_POST['webadd'])); $email = mysqli_real_escape_string($dbc, trim($_POST['email'])); $old_picture = mysqli_real_escape_string($dbc, trim($_POST['old_picture'])); $new_picture = mysqli_real_escape_string($dbc, trim($_FILES['new_picture']['name'])); $new_picture_type = $_FILES['new_picture']['type']; $new_picture_size = $_FILES['new_picture']['size']; $username = mysqli_real_escape_string($dbc, trim($_POST['username'])); $user_id = mysqli_real_escape_string($dbc, trim($_POST['user_id'])); if (!empty($_FILES['new_picture']['tmp_name'])) {list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']); } //list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']); $error = false; // Validate and move the uploaded picture file, if necessary if (!empty($new_picture)) { if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') || ($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) && ($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) { if ($_FILES['new_picture']['error'] == 0) { // Move the file to the target upload folder $target = MM_UPLOADPATH . basename($new_picture); if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) { // The new picture file move was successful, now make sure any old picture is deleted if (!empty($old_picture) && ($old_picture != $new_picture)) { } } else { // The new picture file move failed, so delete the temporary file and set the error flag @unlink($_FILES['new_picture']['tmp_name']); $error = true; echo '<p class="error">Sorry, there was a problem uploading your picture.</p>'; } } } else { // The new picture file is not valid, so delete the temporary file and set the error flag @unlink($_FILES['new_picture']['tmp_name']); $error = true; echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) . ' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>'; } } $error = false; // Update the profile data in the database if (!$error) { if (!empty($name)&& !empty($phone) && !empty($address1) && !empty($address2)) { // Only set the picture column if there is a new picture if (!empty($new_picture)) { //if (!empty($postcode)){ $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', picture = '$new_picture', username = '$username' WHERE user_id = '" . $row['user_id'] ."'"; }} else { $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', username = '$username' WHERE user_id = '" . $row['user_id'] ."'"; } mysqli_query($dbc, $query) or die("<br>Query $query<br>Failed with error: " . mysqli_error($dbc) . '<br>On line: ' . __LINE__); // Confirm success with the user echo '<p>Your profile has been successfully updated. Would you like to <a href="viewprofile4.php">view your profile</a>?</p>'; mysqli_close($dbc); exit(); } else { echo '<p class="error">You must enter all of the profile data (the picture is optional).</p>'; } } // End of check for form submission else { // Grab the profile data from the database $query="SELECT * FROM antique WHERE user_id= '" . $row['user_id'] . "'"; $data = mysqli_query($dbc, $query); $row = mysqli_fetch_array($data); if ($row != NULL) { $name = $row['name']; $phone = $row['phone']; $address1 = $row['address1']; $address2 = $row['address2']; $postcode = $row['postcode']; $email = $row['email']; $webadd = $row['webadd']; $old_picture = $row['picture']; $username = $_SESSION['username']; $user_id = $row['user_id']; } else { echo '<p class="error">There was a problem accessing your profile.</p>'; } } mysqli_close($dbc); ?> <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MM_MAXFILESIZE; ?>" /> <fieldset> <legend>Personal Information</legend> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br /> <label for="phone">Phone:</label> <input type="text" id="phone" name="phone" value="<?php if (!empty($phone)) echo $phone; ?>" /><br /> <label for="address1">Address1:</label> <input type="text" id="address1" name="address1" value="<?php if (!empty($address1)) echo $address1; ?>" /><br /> <label for="address2">Address2:</label> <input type="text" id="address2" name="address2" value="<?php if (!empty($address2)) echo $address2; ?>" /><br /> <label for="postcode">Postcode:</label> <input type="text" id="postcode" name="postcode" value="<?php if (!empty($postcode)) echo $postcode; ?>" /><br /> <label for="email">Email:</label> <input type="text" id="email" name="email" value="<?php if (!empty($email)) { echo $email; } else { echo 'No email entered';} ?>" /><br /> <label for="webadd">Web address:</label> <input type="text" id="webadd" name="webadd" value="<?php if (!empty($webadd)) { echo $webadd; } else { echo 'No web entered';} ?>" /><br /> <input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" /> <label for="new_picture">Pictu </label> <input type="file" id="new_picture" name="new_picture" /> <?php if (!empty($old_picture)) { echo '<img class="profile" src="' . MM_UPLOADPATH . $old_picture . '" alt="Profile Picture" style: height=100px;" />'; } ?> <br /> <label for="address2">username:</label> <input type="text" id="username" name="username" value="<?php if (!empty($username)) echo $username; ?>" /><br /> <label for="user_id">User ID:</label> <input type="text" id="user_id" name="user_id" value="<?php echo '' . $row['user_id'] . '' ; ?>" /><br /> </fieldset> <input type="submit" value="Save Profile" name="submit" /> </form> <?php echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. <a href="logout3.php">Log out</a>.</p>'); echo '<class = "label">USER ID: ' . $row['user_id'] . ''; ?> <p><a href="index.php">Return to homepage</a></p> <?php require_once('footer.php'); ?> </body> </html> Hi, Apologies to keep going on about this but I have hit a brick wall over updating my database with XML. I have spent around 100 hours on this and so far I can only copy the file, I am unable so far to update my database with the information from the XML file. I would be very grateful for any help you can offer to fix this. Code: [Select] ----Code so far----> $xmlReader = new XMLReader(); $filename = "datafeed_98057.xml"; $url = "http://www.domain.co.uk/datafeed.xml"; file_put_contents($filename, file_get_contents($url)); $xmlReader->open($filename); while ($xmlReader->read()) { switch ($xmlReader->name) { case'prod': $dom = new DOMDocument(); $domNode = $xmlReader->expand(); $element = $dom->appendChild($domNode); $domString = utf8_encode($dom->saveXML($element)); $prod = new SimpleXMLElement($domString); $id = $prod->prod['id']; $description = $prod->name; $image = $prod->awImage; $fulldescription = $prod->desc; //insert query if(strlen($prod) > 0) { $query = mysql_query("REPLACE INTO productfeed (id, description, fulldescription, image) VALUES ('$id','$description','$image','$fulldescription') "); echo $id . "has been inserted </br>"; } else{echo ("This does not work </br>");} } This is an outline of the XML feed I am using, it only includes one item which I am using as a test: Code: [Select] - <merchant id="1829" name="Pinesolutions.co.uk"> - <prod id="39920873" pre_order="no" web_offer="no" in_stock="yes" hotPick="no" adult="no"> - <text lang="EN"> <name>Oakleigh Wall Mirror 60x90</name> <desc>Mirrors are useful anywhere in the house. Not only are they functional allowing you to see your reflection in order to look your best, they also add elegance to any room theyre placed in. We offer a variety of mirrors to fit your decorating tastes as well as wall space. The Oakleigh Wall Mirror radiates an elegant simplistic style, while offering a generous size glass. The Oakleigh Wall Mirror s frame is crafted from solid hardwood and is lacquered with a protective finish to guard against dust and unexpected stains. The Oakleigh Wall Mirror is versatile and can be hung portrait style at the top of a staircase or landscape. The Oakleigh Wall Mirrors light colour means it also complements all of the furniture in our Camden Painted Range because the range has ash tops. The Oakleigh Wall Mirror has fewer knots than traditional oak wood, but is built just as sturdy so you can be certain it will last you through the generations to come.</desc> </text> - <uri lang="EN"> <awTrack>http://www.awin1.com/pclick.php?p=39920873&a=98057&m=1829</awTrack> <awImage>http://images.productserve.com/preview/1829/39920873.jpg</awImage> <mLink>http://www.pinesolutions.co.uk/bedroom-furniture/mirrors/wall-mirrors/oakleigh-wall-mirror-60x90/</mLink> <mImage>http://media.pinesolutions.co.uk/images/products/903.333.3.4.jpg</mImage> </uri> - <price curr="GBP"> <buynow>40.00</buynow> </price> - <cat> <awCatId>424</awCatId> </cat> <brand /> </prod> </merchant> Hi, Does anyone have any experience of using PHP to transfer data from an XML file to a MySQL database? For the last 5 weeks I have been trying to get the following code to work but I am still unable to do it. The code does copy the file from my root folder into another (I eventually plan to use external download onto my server). However, it comes up with the following error: "Cannot instantiate non-existent class: xmlreader in" which refers to this: $xmlReader = new XMLReader(); Does anyone have any experience of transferring data from an XML file to a database? I am using PHP 5 so I dont know why this doesn't work. <?php ini_set('display_errors', 1); error_reporting(-1); $host="hostname"; // $username="username"; // $password="password"; // $db_name="db"; // $tbl_name="productfeed"; // // Connect to server and select database. mysql_connect("$host", "$username", "$password")or ("no connection"); mysql_select_db("$db_name")or die("Database Connection Error"); $xmlReader = new XMLReader(); $filename = "datafeed_98057.xml"; $url = "[url=http://www.ukhomefurniture.co.uk/datafeed.xml]http://www.ukhomefurniture.co.uk/datafeed.xml[/url]"; file_put_contents($filename, file_get_contents($url)); $xmlReader->open($filename); while ($xmlReader->read()) { switch ($xmlReader->name) { case'prod': $dom = new DOMDocument(); $domNode = $xmlReader->expand(); $element = $dom->appendChild($domNode); $domString = utf8_encode($dom->saveXML($element)); $product = new SimpleXMLElement($domString); $product_code = $product->prod['id']; $image = $product->awImage; //insert query if(strlen($product) > 0) { $query = mysql_query("REPLACE INTO productfeed (image) VALUES ('$awImage')"); echo $awImage . "has been inserted </br>"; die('yes it works'); error_reporting(E_ALL); if (ini_get('display_errors')) { ini_set('display_errors', 1); } } break; } } ?> MOD EDIT: DB credentials removed. Hi I am trying my first OOP update. I have it working exactly as I want except for one thing. For some reason if I try to update the database with the same information (every column exactly the same) it returns 0 affected rows. is there anyway of getting the database to update, even if all columns are exactly the same? Code: Code: [Select] $membershipID = Profile_membership::find_membership_ID($UID); $MID = $membershipID->id; $new_member = Profile_membership::make($MID, $UID, $acc_type, $membership, $upgradeL, $date, $dateUpgraded); if($new_member && $new_member->save()){ $flag = 1; }else{ $message .= "Error: Sorry, there was an error creating your membership. <br> Please try again<br>"; $flag = 0; } $new_member->save() will create the database entry if no ID exists, and will update if an ID does exist. So, I want the save() to return success. If it does, move on else give an error. However, I'm getting the error, if a user accidentally clicks submit, when no fields have been changed. I what it to still update, so $flag will be 1 Thanks |