PHP - Help Me With Update Records In Mysql Database
I have a problem .
I 've been trying for a long time to make an update for php mysql to change the data. but every time I do not manage to make it work with a form. but it works if I only if I put this ($ sql = "UPDATE users SET username = 'value' WHERE id = 10 " ; ) so it only works when I put the value of the id. but I want in an html form to indicate what I want to change and what id goes. but I have tried so long that I do not feel like I so want someone help me. make the same database and same as my records and make the code and test it if it works show me please my database name : web test my table called : users my records are called : id int ( 11) AUTO_INNCREMENT username , varchar ( 255 ) password , varchar ( 255 ) first_name , varchar ( 255 ) last_name , varchar ( 255 ) email, varchar ( 255 ) Age, int ( 11) Look, my update.php is like this now <?php $servername = "localhost"; $username = "root"; $password = "....."; $dbname = "webtest"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "UPDATE users SET password='cotton candy' WHERE id=10"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close(); ?> but now i have still have to go into the php file to change the valeu or the id but i looked on site and youtube how to put it in a simple html form but it still does not work. i want it in a html from. I want that when I enter the ID that the data of the user appears and that I can change any valeu separately. Similar TutorialsHi guys, I am trying to UPDATE some records on a mySQL database but can't seem to find out why it is not working. This is my code. Code: [Select] <?php $latitude = $_POST['lat_location']; $longitude = $_POST['long_location']; $unique_ID = $_POST['unique_ID']; include('connect2.php'); $query = mysql_query("SELECT * FROM user_location WHERE unit = '$unique_ID'"); $numrows = mysql_num_rows($query); if ($numrows == 1) { $query2="UPDATE user_location SET lat = '$latitude', long = '$longitude' WHERE unit = '$unique_ID'"; mysql_query($query2); $test = "matches"; } else { mysql_query("INSERT INTO user_location VALUES ('','$unique_ID','$latitude','$longitude')"); $test = "not match"; } echo $test . "<br />"; echo $numrows; ?> The script receives the data via the POST method and assigns it to variables. Then I query the database for one of those variables and check how many results are found. If 0 results are found then a new record is created on the database, but if there is 1 record found then the record that is found has to be UPDATED. When the result is 0 the scripts creates the new record fine, but if the result is 1 it doesn't update. I just can't figure out why. Any help will be greatly appreciated. Thanks in advanced, Code: [Select] <?php require "db/config.php"; $fname = $_POST['fname']; $lname = $_POST['lname']; $country = $_POST['country']; $state = $_POST['state']; $city = $_POST['city']; $zcode = $_POST['zcode']; $address = $_POST['address']; $ppemail = $_POST['ppemail']; $pnumber = $_POST['pnumber']; $cemail = $_POST['cemail']; $url = $_POST['url']; $price = "$5.00"; $query = "INSERT INTO custpackage1000( id, FirstName, LastName, Country, State, City, ZipCode, Address, PayPalEmail, PhoneNumber, PrimaryEmail, WebsiteURL) VALUES ( '1', '$fname', '$lname', '$country', '$state', '$city', '$zcode', '$ppemail', '$pnumber', '$cemail', '$url')"; mysql_connect($host, $user, $pass) or die("<br /><br /><h1>Fatal error. Please contact support if this persists.</h1>"); mysql_select_db($dbname); mysql_query($query) or die ("could not open db".mysql_error()); sleep(2); ?> Why won't the code insert into my database upon submission of data? What am I doing wrong? I'm having problems updating my database, I have 4 fields i want to change. I checked all the { on the page, that's not the problem, I tried to echo information from the database and it displayed my information so that's not the problem, i tried yelling at my computer, that didn't work, i tried to input data into the database with the insert function it worked but is not practical in my situation. I'm probably going to face palm when i find out whats wrong, help please btw, the $_SESSION['usr'] was set in another page and works. Code: [Select] <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Edit Info</title> <link rel="stylesheet" type="text/css" href="demo.css" media="screen" /> </head> <body> <div id="main"> <div class="container"> <font size="5" face="sans-serif">Change Settings <?php echo "{$_SESSION['usr']}"; ?></font> <form action="" method="POST"> <table cellpadding="3" cellspacinf="4" border="0"> <tr> <td>Name</td> <td><input type="text" name="name" /></td> </tr> <tr> <td>Age</td> <td><input type="text" name="age" /></td> </tr> <tr> <td>Gender</td> <td><input type="text" name="mf" /></td> </tr> <tr> <td>Location</td> <td><input type="text" name="loc" /></td> </tr> <tr> <td><input type="submit" name="submit" value="submit" /></td> </tr> </table> </form> <?php if ($_POST['submit']){ define('INCLUDE_CHECK',true); require 'connect.php'; $usr = $_SESSION['usr']; $sql = mysql_query("UPDATE members SET name='{$_POST['name']}', age='{$_POST['age']}, mf='{$_POST['mf']}', loc='{$_POST['loc']}' WHERE usr='{$_SESSION['usr']}'"); if($sql){ echo 'Changes Saved!'; }else{ echo 'Error'; } } ?> </div> </div> </body> </html> Hello all, first post here so i hope i'm doing this right and am putting this into the right place. Im in the process of integrating a blog into my website, mostly it's set up however i'm currently working on the code to update the posts (theres only 2 parts a title and a comments[which is in actual fact the post content itself]). The code succsefully completes without any errors but for some reason it does not actually update the mysql database.. the code i'm using is as follows: Code: [Select] <?php require_once('header.php'); include "../blog/blogconfig.php"; if(isset($_POST['submit'])){ $update="UPDATE eq_blogarticle SET title='".$_POST['title']."',comments='".$_POST['comment']."' WHERE artid='$aid'"; if(!mysql_query($update)){ echo mysql_error(); }else{ header("location:blog.php?action=listmsgs"); exit; } } ?> <?php // get value of aid that sent from address bar by blog.php?action=listmsgs $aid=$_GET['aid']; // Retrieve data from database $sql="SELECT * FROM eq_blogarticle WHERE artid='$aid'"; $result=mysql_query($sql); $row=mysql_fetch_array($result); ?> <form name="form2" method="post" action="update.php"> <script type="text/javascript">var SITE_URL="<?php echo SITE_URL;?>";</script> <script type="text/javascript" src="<?php echo SITE_URL;?>/includes/js/nicEdit.js"></script> <script type="text/javascript"> //<![CDATA[ bkLib.onDomLoaded(function() { nicEditors.allTextAreas() }); //]]> </script> <body> <table width="100%" border="0" cellspacing="1"> <tr> <td colspan="2" class="temptitle">Equidisc Blog</td> </tr> <tr> <td width="74%" valign="top"> <table> Edit Blog Post <br> <br> Title: <br> <input name="title" type="text" class="input" id="title" value="<? echo $row['title']; ?>"> <br> <br> <span class="style1 style2 style3">Blog Post:</span> <br> <br> <textarea name="comments" cols="55" rows="12" class="input" id="comments"><? echo stripslashes($row['comments']); ?></textarea> <br> <br> <input name="aid" type="hidden" id="aid" value="<? echo $row['artid']; ?>"> <input type="submit" name="submit" value="Submit"> </form> </table> </td> <td width="26%" valign="top"><table width="100%" border="0" cellspacing="1"> <tr> <td colspan="2"><img src="../blog/images/fb.gif" width="16" height="16" /> <strong>Blog Menu</strong></td> </tr> <tr> <td><a href="blog.php">Home</a></td> </tr> <tr> <td><a href="blog.php?action=newblogpost">New Post </a></td> </tr> <tr> <td><a href="blog.php?action=listmsgs">Manage Posts </a></td> </tr> </table></td> </tr> </table> </body> <?php require_once('footer.php'); ?> Explanation: header/footer.php obvious ../blog/blogconfig.php holds my mysql connection settings and connects to the sql, this is the same config as is used for creating the new posts which i have no issues with so i dont think the issue lays there. If i run the query on phpmyadmin with dummy data it works fine and updates the entry.. Any help would be very much appreciated as i'm at the end of my tether with this!. Thanks in advance. Jo Hi, Im just in the middle of creating an update script for my mysql database but don't know why it's not working. p.s. I'm a little new to PHP, but know quite a bit, it's probably something really small.. *facepalm* Here's the script: the form (update.php) <? // Connect to the database $link = mysql_connect('###', '###', '###'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('###', $link); $id = $_GET['id']; // Ask the database for the information from the links table $query="SELECT * FROM orders WHERE id='$id'"; $result = mysql_query("SELECT * FROM orders"); $num=mysql_numrows($result); mysql_close(); $i=0; while ($i < $num) { $name=mysql_result($result,$i,"Name"); $location=mysql_result($result,$i,"Location"); $fault=mysql_result($result,$i,"Fault"); ?> <form action="updated.php" method="post"> <input type="hidden" name="ud_id" value="<? echo "$id";?>"> Name: <input type="text" name="ud_name" value="<? echo "$name"?>"><br> Location: <input type="text" name="ud_location" value="<? echo "$location"?>"><br> Fault: <input type="text" name="ud_fault" value="<? echo "$fault"?>"><br> <input type="Submit" value="Update"> </form> <? ++$i; } ?> ------------------------------------------------------ (processor) updated.php <?php // Connect to the database $link = mysql_connect('###', '###', '###'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('###', $link); $query="UPDATE orders SET Name='" . $_POST['ud_name'] . "', Location='" . $_POST['ud_location'] . "', Fault='" . $_POST['ud_fault'] . "' WHERE $id='" . $_POST['ud_id'] . "'"; echo $query; $checkresult = mysql_query($query); if ($checkresult) echo '<p>update query succeeded'; else echo '<p>update query failed'; mysql_close(); ?> ------------------------------------------------------ Every time I want to update, it comes up with: UPDATE orders SET Name='TEST', Location='TEST', fault='jbjh' WHERE ='' update query failed Any help would be appreciated. Hi. I'm trying to use UPDATE to update my datebase. When I run the code inside mysql phpadmin it works fine. But when I try and run something similiar from my php page its not updating. UPDATE user SET password='newpass', verified='0', random='asldk445435' WHERE email='email@email.com' This is the section that isn't working: // Thank you Page //generate new random number for activation process $randomcode = md5(rand(23456789,987654321)); // generate a new random password $newtemppass = createRandomPassword(); // encrypes new password $newtemppass = md5(rand(23456789,987654321)); $random = $randomcode; $verified = "0"; // Setup query to update datebase $query = "UPDATE {$usertable} SET password='$newtemppass', verified='$verified', random='$random' WHERE email='matt@flemingds.com' "; echo "<p>--------------</p>"; echo "<p>--------------</p>"; echo $newtemppass .' '.'This is your new password'; echo "<p>--------------</p>"; echo $verified .' '.'You are no longer verfied'; echo "<p>--------------</p>"; echo $random .' '.'New Random Code'; echo "<p>--------------</p>"; If you need the rest of my code. <?php //IF SUMBIT = TRUE THEN //IF USER_CODE = TRUE THEN //IF SALON NAME <> BAD CHARACTERS THEN //IF EMAIL = EMAIL IN DATEBASE THEN //CHANGE RANDOM CODE IN DATEBASE //SEND ID,SALONNAME,EMAIL,RANDOM_CODE TO EMAIL FROM DATEBASE //ELSE //EMAIL ADDRESS IS NOT IN DATABASE //STOP CODE //ELSE //SALON NAME IS INCORRECT, TRY AGAIN //STOP CODE //ELSE //PLESE RE-ENTER THE SECUIRTY CODE" CASE SENSITIVE //STOP CODE //ELSE //STOP END CODE ?> <?php // Start Session session_start(); ?> <?php $submit = $_POST['submit']; // Form Data $email = strip_tags($_POST['email']); $salonname = strip_tags($_POST['salonname']); if ($_POST[submit]) { echo "TRUE - CONTINUE_1 "; echo "<p>--------------</p>"; //echo $_SESSION[key].' - '.$_POST[user_code].'<br>'; if ($_SESSION[key]==$_POST[user_code]) { echo "TRUE - CONTINUE_2 "; echo "<p>--------------</p>"; $_SESSION[key]=''; if ($salonname) { echo "TRUE - CONTINUE_3 "; echo "<p>--------------</p>"; $email = trim($_POST['email']); if(!checkEmail($email)) { echo("Invalid email address!"); } else { // ENTER INFORMATION INTO DATEBASE include "dbConfig.php"; // table is mysql table, WHERE FIELD_NAME ='text'" OR =>='10'"; or VAR = '.$variable.') // SQL grabs records // * means "ALL RECORDS" or use FIELD_NAME, FIELD_NAME2 instead of * // $usertable = user where user is the TABLE // use WHERE FIELD_NAME = '$email' variable $SQL = "SELECT email,id,random,salonname FROM {$usertable} WHERE email = '{$email}' "; // mysql_query() is used to send a SQL query to database and returns TRUE or FALSE, or FILE HANDLE if using SELECT // $result = mysql_query($SQL); only POINTS to results $result = mysql_query($SQL) or die(mysql_query()); // mysql_fetch_assoc($result) GETS RESULTS from $result // assoc or associative array brings keys as text Array['One'] =, Array['Two']= and NOT Array[1]= // Place results into $db_field Array $db_field = mysql_fetch_assoc($result); if ($email <> $db_field['email']) { die($email .' '.'is not in database!'); } else $errorstop="go"; echo "<p>--------------</p>"; echo $db_field['id'] .' '.'This is your ID!'; echo "<p>--------------</p>"; echo $db_field['salonname'] .' '.'This is your Salon Name!'; echo "<p>--------------</p>"; echo $db_field['random'] .' '.'This is your random code'; echo "<p>--------------</p>"; echo $db_field['email'] .' '.'will be sent an Email!'; // Thank you Page //generate new random number for activation process $randomcode = md5(rand(23456789,987654321)); // generate a new random password $newtemppass = createRandomPassword(); // encrypes new password $newtemppass = md5(rand(23456789,987654321)); $random = $randomcode; $verified = "0"; // Setup query to update datebase $query = "UPDATE {$usertable} SET password='$newtemppass', verified='$verified', random='$random' WHERE email='matt@flemingds.com' "; echo "<p>--------------</p>"; echo "<p>--------------</p>"; echo $newtemppass .' '.'This is your new password'; echo "<p>--------------</p>"; echo $verified .' '.'You are no longer verfied'; echo "<p>--------------</p>"; echo $random .' '.'New Random Code'; echo "<p>--------------</p>"; } } else { // STOP CODE echo "FALSE - STOP_3 SALON NAME INVALID"; }// End salonanme check } else { echo "FALSE - STOP_2 INVALID SECUIRTY CODE"; }// End user code }// End if Sumbit else {// STOP CODE echo "FALSE - STOP_1 PLEASE FILL IN ALL FIELDS"; } ?> <?php // LINUX PLATFORM OPTION 3 // checkEmail function checks standard email format same as preg_match() // checkEmail function checks DSN records using checkdnsrr Use list() to seperate name and domain using split function // checkdnsrr ONLY WORKS on LINUX PLATFORM // Check to see if domain and username is active // uses fsockopen() to check if its in use using port 25 function checkEmail($email) { // checks proper syntax if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/" , $email)) { // gets domain name list($username,$domain)=split('@',$email); // checks for if MX records in the DNS if(!checkdnsrr($domain, 'MX')) { return false; } return true; } return false; } ?> <?php /** * The letter l (lowercase L) and the number 1 * have been removed, as they can be mistaken * for each other. */ function createRandomPassword() { $chars = "abcdefghijkmnopqrstuvwxyz023456789"; srand((double)microtime()*1000000); $i = 0; $pass = '' ; while ($i <= 7) { $num = rand() % 33; $tmp = substr($chars, $num, 1); $pass = $pass . $tmp; $i++; } return $pass; } // Usage //$password = createRandomPassword(); //echo "Your random password is: $password"; ?> Hi everyone, I have been trying to get this code working but no matter what I try it will not work, I am trying to allow a user to update their personal details when they login to my website. I have created a form and submit button, the code is shwn below: <?php echo $_SESSION['myusername']; ?> <br><br> <form action="updated.php" method="post"> Firstname: <input type="text" name="firstname" /><br><br> Surname : <input type="text" name="surname" /><br><br> Date Birth: <input type="text" name="dob" /><br><br> Total Wins: <input type="text" name="wins" /> Total Loses: <input type="text" name="loses" /><br><br> Email Add: <input type="text" name="email" /><br><br> Country : <input type="text" name="born" /><br><br> Other Info: <input type="text" name="other" /><br><br> <input type="submit" name="Submit" value="Update" align="right"></td> </form> The updated.php file <?php mysql_connect ("localhost","root","") or die("Cannot connect to Database"); mysql_select_db ("test"); $sql=mysql_query("UPDATE memberdetails SET firstname='{$_POST['firstname']}', surname='{$_POST['surname']}', dob='{$_POST['dob']}', totalwins='{$_POST['wins']}', totalloses='{$_POST['loses']}', email='{$_POST['email']}', country='{$_POST['born']}', info='{$_POST['other']} WHERE username=$_SESSION['myusername']); if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } echo "Details Updated"; ?> This is the error i recieve: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\wamp\www\website\updated.php on line 45 Line 45 is $sql=mysql_query line If anybody can help it will be very much appreciated! I am writing a code for a page which will get certain information from database into fields and update edited information. I can get information from database, but cannot update the edited information to database. Please, Can anyone help me ? Code: [Select] <? session_start(); include("includes/connection.php"); include("includes/config.php"); $sqlsettings = "SELECT * from admin"; $resultsettings = mysql_query($sqlsettings); $rowsettings = @mysql_fetch_array($resultsettings); if ($_SESSION['MyAccount']=='') { $_SESSION['MyAccount'] = "MyAccount"; header('LOCATION: login.php'); exit(); } $msg=''; if($_POST['continue'] == "true") { $AddedDate = $_POST['AddedDate']; $sqlUpdate = "UPDATE buyer_career SET CareerTitle='".mysql_real_escape_string($_POST['CareerTitle'])."', CareerDescription='".mysql_real_escape_string($_POST['CareerDescription'])."', ExpiryDate='".mysql_real_escape_string($_POST['ExpiryDate'])."', where BuyerCareerID=".$_POST['BuyerCareerID']; $result=mysql_query($sqlUpdate); header("Location:buyers_career.php?msg=Buying Lead has been updated successfully"); exit(); } ?> <? //retreiving data from selling leads $sqlBuyingLead="select * from buyer,buyer_career where buyer.BuyerID=buyer_career.BuyerID and BuyerCareerID=".$_GET['BuyerCareerID']; $resultBuyingLead=mysql_query($sqlBuyingLead); $buying_row=@mysql_fetch_array($resultBuyingLead); ?> <form name="PostNewCareer" method="post" action="edit_buyer_career.php" enctype="multipart/form-data" onSubmit="return validate(this);"> <input type="text" name="CareerTitle" style="width: 400px" class="basicPoint" id="CareerTitle" value="<?=$buying_row['CareerTitle']?>" /> <input type="hidden" name="AddedDate" value="<?=$buying_row['AddedDate']?>"> <input type="text" name="CareerVacancies" style="width: 400px" class="basicPoint" id="CareerVacancies" value="<?=$buying_row['CareerVacancies']?>"/> <input type="hidden" name="continue" value="true"> <input type="hidden" name="BuyerCareerID" id="BuyerCareerID" value="<?=$_GET['BuyerCareerID']?>"/> <input type="submit" value="Update Buying Lead" name="submitButton" /> Has anyone got any script or refence to a tut where i can find a script that compares two mysql database (current) and outdated db and then takes the current db and updates the outdated one to match accordingly. Thanks Hello everyone I need code for this question
would you help me please..?
I am really not sure if this is a problem with me (probably is), php or mysql. I have a calendar that I am adding events to. If I want to edit only the date I can but only once after I make this update I am out. If I attempt to update the time or event title the database is never updated and I am no longer able to update the date. here is the controller for the save. Code: [Select] <?php function eventsave() { $details = $_POST; $this->load->model('eventsmodel'); $this->eventsmodel->eventsave($details,'', TRUE); redirect('/admin/events', 'location'); } ?> I have turned off the redirect to see if I was getting any errors and they seem to be non existent. Here is the model that is used to create a new entry and update a record. Code: [Select] <?php function eventsave($event) { $startdate = explode('-', $event['startdate']); $start = mktime($event['starthour'], $event['startmin'], 0, $startdate['0'], $startdate['1'], $startdate['2']); $end = mktime($event['endhour'], $event['endmin'], 0, $startdate['0'], $startdate['1'], $startdate['2']); $name = $event['name']; if (isset($event['id'])) { // if is true then this is an update not a new event $data = array( 'name' => $name, 'start' => $start, 'end' => $end ); $this->db->where('id', $id); $this->db->update('events', $data); }else{ $this->db->set('name', $name); $this->db->set('start', $start); $this->db->set('end', $end); $this->db->insert('events'); } } ?> I am using code igniter if that helps and the information being submitted by the form looks good. This is the submitted update array and the new event array is just missing the "id" Code: [Select] Array ( [name] => test [startdate] => 05-14-2011 [starthour] => 1 [startmin] => 0 [endhour] => 1 [endmin] => 0 [id] => 54 [saveevent] => save ) Any suggestions would be appreciated. Thank you. Hi all, I'm trying to make a query that allows the user to edit the name of a entry in SQL. I believe I have the corect Syntax but I'm not sure if I have the code set up correctly. I am using 2 queries when I think it is possible with one. The first query is used to Pint out results for a certain year and the second to update the names. Code: [Select] $desiredYear = $_POST['year']; $nameEdit = $_POST['edit']; $origName = $_POST['orig']; echo ' The year you have chosen is '.$desiredYear; $describeQuery = "SELECT ID, Name, (SELECT SUM(SalesVolume) as SalesVolume FROM MonthlySales WHERE ProductCode=Products.ID AND Year = '$desiredYear') AS num_sales FROM Products"; $editQuery = "UPDATE Products SET Name = '$nameEdit' WHERE Name ='$origName'"; $results = sqlsrv_query($conn, $describeQuery); echo '<table border="1" BORDERCOLOR=Black>'; echo '<tr><th bgcolor = "LightBlue">Name</th><th bgcolor = "LightBlue" >ID</th> <th bgcolor = "LightBlue" >Sales</th></tr>'; while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC)) { echo '<tr>'; echo '<td >' .$row['Name'].'</td>'; echo '<td>' .$row['ID'].'</td>'; echo '<td>' .$row['num_sales'].'</td>'; echo '</tr>'; } echo '</table>'; sqlsrv_close($conn); Can somebody help me with this? Thank you Hi there, Im fairly new at php and mysql but nevertheless im trying to build a web based campaign game for starwars minatures boardgame. Its fairly straightforward and going well.. However ive been thinking about how it will work and have stumbled across a possible problem (because of my limited craft at programming). I want to have a single form that updates all records in the tables, this would simulate an "end of turn" button. Im sure i can do this if doing stuff in the game (e.g. move, create , modify, delete, fleets/ships and auto increment ships hulls simulating repair) if it was done on the same page. However i wanted to to initiate some of these adjustments in their respective pages (fleet.php, planets.php, ships.php etc) and then once the user is happy to click the end turn button somewhere which would update all of these things at the same time.. Is this possible at all??? If anybody could help that would be brilliant. Thank you p.s. if anybody wants a copy of the finished product when its complete, your most welcome. Hi ive been stuck for a while now and i just cant get my head around it so if you could help i'd be well chuffed. I'm trying to update multple rows in a table depending upon the results of another. I have a form that enables me to update a table called fleet. Another table called ships is realted to the fleet table as each ship is in a fleet: fleet ----- Fleetname* Location Detected ships ------ ShipID* Fleetname * Shipname The particular fleet i am editing is parsed as a url parameter. I made a query to search for all the ships that are in the fleet i am editing: Code: [Select] $colname_ShipsInfleet = "-1"; if (isset($_GET['recordID'])) { $colname_ShipsInfleet = (get_magic_quotes_gpc()) ? $_GET['recordID'] : addslashes($_GET['recordID']); } mysql_select_db($database_swb, $swb); $query_ShipsInfleet = sprintf("SELECT * FROM ships WHERE FleetName = %s", GetSQLValueString($colname_ShipsInfleet, "text")); $ShipsInfleet = mysql_query($query_ShipsInfleet, $swb) or die(mysql_error()); $row_ShipsInfleet = mysql_fetch_assoc($ShipsInfleet); $totalRows_ShipsInfleet = mysql_num_rows($ShipsInfleet); It searched the ships WHERE the FleetName (which is the primary key of the fleet table) is parsed as a url parameter. The appropriate ship records that are generated i want to use so a field can be updated. For example im updating a fleet record and and setting the location (Planet Name) to a different value. I want the Ship records that are of that particular fleet to update a field (PlanetName) in ship table when the fleet table is updated. Code: [Select] if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) { $updateSQL = sprintf("UPDATE ships WHERE ShipID = $row_ShipsInfleet['ShipID'] SET PlanetName=%s", GetSQLValueString($_POST['select'], "text")); mysql_select_db($database_swb, $swb); $Result1 = mysql_query($updateSQL, $swb) or die(mysql_error()); $updateSQL = sprintf("UPDATE fleet SET PlanetName=%s, Detected=%s, Faction=%s WHERE FleetName=%s", GetSQLValueString($_POST['select'], "text"), GetSQLValueString(isset($_POST['checkbox']) ? "true" : "", "defined","1","0"), GetSQLValueString($_POST['hiddenField2'], "int"), GetSQLValueString($_POST['hiddenField'], "text")); mysql_select_db($database_swb, $swb); $Result1 = mysql_query($updateSQL, $swb) or die(mysql_error()); I'm really not sure how to proceed here so please if you can help me out that would be ace. Thank You Hi there, hope have some help. I have a form where a user select time and days of the week (monday, tuesday..) that he is available. The insert script works fine, it insert and the days of week he checked in the table, the only problme is when i try to update each of them.
I used this code above, but is not working, instead of updating/inserting days that is selected is inserting multi-records with the same day of the week value.
here it is:
foreach($weekDay as $DaysofWeek){ $sql_days = "UPDATE available SET day_time = '$day_time', week_day = '$DaysofWeek' WHERE user_id = '$id_user'"; $update_availability = mysql_query($sql_days); } Hi is it possible to update multiple records of the same table using a single hidden field with a while loop??? For example: Code: [Select] <?php if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) { $updateSQL = sprintf("UPDATE ships SET HealthA=%s WHERE ShipID=%s", GetSQLValueString($_POST['healtha'], "int"), GetSQLValueString($_POST['shipid'], "text")); ?> <input name="healtha" type="hidden" id="healtha" value="<?php echo $row_Ships['HealthA'] + 1; ?>" /> <input name="shipid" type="hidden" id="shipid" value="<?php while($row = mysql_fetch_assoc($Ships)){ echo $row_Ships['ShipID']; }?>" /> If its not possible what else could i do to achieve this please? Thank you Hi i have this simple update form and scrip but somehow it doesnt seem to be update the field on the database can someone help out please. The html form is the second form bellow where the action send to status_update.php HTML FORM Code: [Select] <?php include("../header.html"); ?> <?php include("header_news.html"); extract($_REQUEST,EXTR_SKIP); ?><?php /* print("sfilm_refnum = $sfilm_refnum<BR>"); print("sfilm_addr01 = $sfilm_addr01<BR>"); print("sfilm_postcode = $sfilm_postcode<BR>"); print("Film Client = $fclient<BR>"); */ ?> <form id="search" action="list.php" method="post" name="search"> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td align="right" width="140"></td> <td width="320"><span class="hofblack10"> </span> </td> <td align="center" width="100"><input type="hidden" name="lstart" value="<?php print("$lstart"); ?>" /><input type="hidden" name="lend" value="<?php print("$lend"); ?>" /><input type="hidden" name="lamount" value="<?php print("$lamount"); ?>" /></td> <td align="center" width="100"></td> <td align="right"></td> </tr> </table> </form> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#4050c4"> <tr> <td width="60" class="hofwhite10">action</td> <td width="140"><span class="hofwhite14">DATE</span></td> <td width="80"><span class="hofwhite14">ID</span></td> <td><span class="hofwhite14">News Titile</span></td> <td width="100"><span class="hofwhite14">Status</span></td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table><table width="780" border="0" cellspacing="0" cellpadding="4"><tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> <tr height="0"> <td width="60" height="0"></td> <td width="80" height="0"></td> <td height="0"></td> <td align="right" width="120" height="0"></td> </tr> </table> <?php //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select DATABASE."); $query2="SELECT * FROM news WHERE !(news_status='deleted')"; $result2 = mysql_query($query2) or die("Couldn't execute QUERY - Select NEWS Qty"); $fqty = mysql_num_rows($result2); //SELECT or FIND the same USERNAME $query3="SELECT * FROM news WHERE !(news_status='deleted') ORDER BY news_id DESC"; $result3 = mysql_query($query3) or die("Couldn't execute QUERY - Select NEWS"); while ($row = mysql_fetch_array($result3)) { $news_id = $row['news_id']; $news_title = $row['news_title']; $news_story = $row['news_story']; $news_image = $row['news_image']; $news_image_caption = $row['news_image_caption']; $news_image_link = $row['news_image_link']; $news_date_day = $row['news_date_day']; $news_date_month = $row['news_date_month']; $news_date_year = $row['news_date_year']; $news_status = $row['news_status']; $news_website = $row['news_website']; $news_date_created = $row['news_date_created']; $news_date_modified = $row['news_date_modified']; ?> <table width="780" border="0" cellspacing="0" cellpadding="4" bgcolor="#eeeeee"> <tr> <td width="60"><span class="hofblack10"> <?php if($news_status=="deleted"){ print("<a class='hifblack10'>deleted</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>edit</a>"); } ?> </span></td> <td width="140"><span class="titlegrey12"> <?php if(!$news_date_day) { echo "00"; } else{ echo $news_date_day; } echo "/"; if(!$news_date_month) { echo "00"; }else{ echo $news_date_month; } echo "/"; if(!$news_date_year) { echo "0000"; }else{ echo $news_date_year; } ?> </span></td> <td width="80"><span class="titlegrey12"><?php print("$news_id"); ?></span> </td> <td><?php if($news_status=="deleted") { print("<class='hofblack10'>$news_title</span>"); }ELSE{ print("<a class='blueul' href='edit.php?id=$news_id'>$news_title</a>"); } ?></td> <td width="100"> <form id="list_update" action="status_update.php" method="post" name="list_update"> <select name="newnstatus" size="1"> <option <?php if($row['news_status'] == "") { print("selected"); } ?> selected="selected" value="">Status...</option> <option <?php if($row['news_status'] == "on") { print("selected"); } ?> value="on">On</option> <option <?php if($row['news_status'] == "off") { print("selected"); } ?> value="off">Off</option> <option <?php if($row['news_status'] == "deleted") { print("selected"); } ?> value="deleted">Delete</option> </select> <input type="hidden" name="nstatus" value="<?php echo $row[news_status]; ?>" /> <input type="hidden" name="id" value="<?php echo $row[news_id]; ?>" /> <input type="submit" name="update" value="update" /> </form> </td> </tr> <tr height="0"> <td bgcolor="white" width="60"></td> <td bgcolor="white" width="140" height="0"></td> <td bgcolor="white" width="80" height="0"></td> <td bgcolor="white" height="0"></td> <td bgcolor="white" width="100" height="0"></td> </tr> </table> <?php } mysql_close($connection);//}?> <table width="780" border="0" cellspacing="0" cellpadding="4"> <tr> <td width="60"></td> <td width="80"></td> <td><a class="blueullrg" href="add.php">Add News</a></td> <td align="right" width="120"></td> </tr> </table><?php // include("list_navigation.html"); ?> <?php include("../footer.html"); ?> </div></body></html> The action script php Code: [Select] <?php /* echo "fstatus: ".$fstatus."<BR>"; echo "id: ".$id."<BR>"; echo "fclient: ".$fclient."<BR>"; echo "newfstatus: ".$newfstatus."<BR>";*/ //set the date of agreement $timestamp = date('l jS \of F Y h:i:s A'); //get the DB connection variables include("../../../includes/config.php"); //connect to DB $connection = @mysql_connect($db_address,$db_username,$db_password) or die("Couldn't CONNECT."); $db = @mysql_select_db($db_name, $connection) or die("Couldn't select FILMS DATABASE."); // All appears well, so enter into database $query= "UPDATE news SET news_status = '$newnstatus' WHERE news_id='$id'"; $result = mysql_query($query) or die("could not execute query - Update FILMS Record to DB"); //setup an email to the Admin @ hof, w/o attachment $emailto="xx@xxx.co.uk"; $emailfrom="no-reply@xxxx.co.uk"; $emailsubject="xx Record Updated"; $emailmessage="Hello Registrar\n\n"; $emailmessage.="News ID: ".$id."\n"; $emailmessage.="Updated on: ".$timestamp."\n\n"; $emailmessage.="Status was: ".$nstatus."\n"; $emailmessage.="Status now: ".$newfnstatus."\n"; $emailmessage.="Thank you,\n\n"; $emailmessage.="Web Site ROBOT\n"; $emailmessage.="(Administrator)\n"; $emailmessage.="xxx.co.uk | xxx.biz\n"; $emailmessage.="----------------------------------------------\n"; $emailmessage.="e. http://www.xxx.co.uk/contact.php\n"; $emailmessage.="w. http://www.xxx.co.uk\n"; $emailheader="From: xxx.co.uk<$emailfrom>"; $emailheader .= 'Cc: xxx@xxx.co.uk'."\r\n"; $emailheader .= 'Bcc: xxx@xxxxx.co.uk'."\r\n"; $ok=mail($emailto,$emailsubject,$emailmessage,$emailheader); mysql_close($connection); if ($ok) { header("Location: list.php"); /* Redirect browser */ exit; } else { $errmsg="There was a problem, please try later or telephone us direct."; $errsta="1"; include("edit_error.html"); //echo "<p>Mail could not be sent. Sorry!</p>"; exit; } ?> Thanks in advance Hi all Complete noob here..... What I have to do is create a new database every year, but I can't just import last years data completely, only records when needed. I can do it myself in PHPMyAdmin, but I don't want my employees touching mysql directly. What I am trying to do is write a php script that will serach for a reocrd in last years database and if it exists insert it into the new database if it doesn't exists bring up a form so it can be entered. Any help would be greatly appreciated. Thanx ZZ Code: [Select] <?php ob_start(); session_start(); $pagerank=2; if ($rank < $pagerank){ header('Location:main.php?id=lowrank.php'); } else{ $name1 = $_GET["name"]; $type2 = $_GET['type']; Echo "Your seach for ".$name1." gave the following results: "; $records_per_page = 15; $total = mysql_result(mysql_query("SELECT COUNT(*) FROM systems WHERE '$type2' LIKE '%$name1%'"), 0) or die(mysql_error()); $page_count = ceil($total / $records_per_page); Echo $total." Records Found"; echo "<table border=0>"; $page = 1; if (isset($_GET['page']) && $_GET['page'] >= 1 && $_GET['page'] <= $page_count) { $page = (int)$_GET['page']; } $skip = ($page - 1) * $records_per_page; $result = mysql_query("SELECT * FROM systems WHERE $type2 LIKE '%$name1%' ORDER BY Security DESC LIMIT $skip, $records_per_page") or die(mysql_error()); echo "<table border=1>"; echo "<td>System Name</td><td>Security</td><td>Class</td>"; while ($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td valign =top>".$row['System Name']."</td>"; echo "<td valign =top>".round($row['Security'],1)."</td>"; echo "<td valign =top>".$row['System Type']."</td>"; echo "</tr>"; } echo "</table>"; echo "<br>"; for ($i = 1; $i <= $page_count; ++$i) { echo '<a href="main.php?id=' . $_GET['id'] .'&name='.$name1.'&type='.$type1. '&page=' . $i . '">' . $i . '</a> '; } } ?> The above code takes data entered in a form and is suppose to show the matching results, but no records are showing, it works when I replace the $name1 and $type2 with the actual values, any ideas? I created this database Code: [Select] <?php $mysqli = mysqli_connect('localhost', 'admin', 'jce123', 'php_class'); if(mysqli_connect_errno()) { printf("connection failed: %s\n", mysqli_connect_error()); exit(); }else{ $q = mysqli_query($mysqli, "DROP TABLE IF EXISTS airline_survey"); if($q){echo "deleted the table airline_survey....<br>";} else{echo "damm... ".mysqli_error($mysqli);} $sql = "CREATE TABLE airline_survey ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, staff CHAR(10) NOT NULL, luggage CHAR(10) NOT NULL, seating CHAR(10) NOT NULL, clean CHAR(10) NOT NULL, noise CHAR(10) NOT NULL )"; $res = mysqli_query($mysqli, $sql); if($res === TRUE) { echo "table created"; } else { printf("Could not create table: %s\n", mysqli_error($mysqli)); } mysqli_close($mysqli); } ?> When I look at it it looks fine. I have a form that sends data to this script: Code: [Select] <?php $con = mysql_connect('localhost', 'admin', 'abc123'); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("php_class", $con); foreach ($_POST as $key => $value) { $staff = ""; $luggage = ""; $seating = ""; $clean = ""; $noise = ""; switch($key){ case "staff": $staff = $value; break; case "luggage": $luggage = $value; break; case "seating": $seating = $value; break; case "clean": $clean = $value; break; case "noise": $noise = $value; break; default: echo "we must be in the twilight zone"; } echo $staff."<br>"; [color=red] mysql_query("INSERT INTO airline_survey (staff, luggage, seating, clean, noise) VALUES ($staff, $luggage, $seating, $clean, $noise)");[/color] } ?> as you can see right before the insert query I test one of the variables to see if it has the string I'm expecting and it does. The problem is the script runs without giving me an error message but the data never gets inserted into the table. |