PHP - Update.php Not Functioning Properly
Similar Tutorials$db->query( "UPDATE user_resources, user_buildings, user_units_nonbattle SET user_resources.uGold=user_resources.uGold+(user_buildings.uTownCenterLevel*(user_units_nonbattle.uMiner*10))" ); When the cron runs, it updates everyone the same regardless. Any idea what i'm doing wrong? HI, according to my knowledge session_destroy() function would destroy all session variables and mysql_close() would close connection with the database. i make a simply logoff.php file and close myssql connection and destroy session. but i still get values from the database and session variables. and doesnt work properly here is the code Code: [Select] <?php session_start(); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ require_once '../database/db_connecting.php'; $dbname="sahansevena";//set database name $con= setConnections();//make connections use implemented methode in db_connectiong.php mysql_select_db($dbname, $con); //update the time and date of the admin table $update_time="update admin set last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname'limit 3,4"; //my admin table contain 5 colums they are id, username,password, last_logged_date, last_log_time $link= mysql_query($update_time); // mysql_select_db($dbname, $link); //$con=mysql_connect('localhost', 'root','ijts'); $result="select * from admin where username='a'"; $result=mysql_query($result); mysql_close($con); //here i just check after closing data baseconnection whether i do get reselts but i do, why? echo "after the cnnection was closed"; echo "<html>"; echo "<table border='1' cellspacing='1' cellpadding='2' align='center'>"; echo "<thead>"; echo"<tr>"; echo "<th>"; echo ID; echo"</th>"; echo" <th>";echo Username; echo"</th>"; echo"<th>";echo Password; echo"</th>"; echo"<th>";echo Last_logged_date; echo "</th>"; echo "<th>";echo Last_logged_time; echo "</th>"; echo" </tr>"; echo" </thead>"; echo" <tbody>"; while($row= mysql_fetch_array($result,MYSQL_BOTH)){ echo "<tr>"; echo "<td>"; echo $row[0]; echo "</td>"; echo "<td>"; echo $row[1]; echo "</td>"; echo "<td>"; echo $row[2]; echo "</td>"; echo "<td>"; echo $row[3]; echo "</td>"; echo "<td>"; echo $row[4]; echo "</td>"; echo "</tr>"; } echo" </tbody>"; echo "</table>"; echo "</html>"; session_destroy(); session_commit(); echo "session and database are closed but i still get values".$_SESSION['admin']; ?> Problem: My code is not functioning at all on my form. I would like to see why? Scripting Info: Using PHP and MySQL Using offline Server for testing(XAMPP) Using default Server name and login.(localhost,root,[NO PASSWORD]) Database name is reh_temp Table within database is named users 1 Value in table "users" called users Goal: My form has 3 inputs. 2-Text and 1-Submit. The 1st text input has the name of id. And the 2nd input has the name of table. In the PHP/MySQL part the values are inputed as follows: The one with name of "id" gets put into the table users under the users value. The one with name of "table" creates a new table named after what the user inputs The rest of the script is just Character Length checks, Exsistance of value checks, Match check, ect. Here's the code: Code: [Select] <?php $connect1 = mysql_connect("localhost","root",""); if (!$connect) die('Could not connect to the database: ' . mysql_error()); $id = $_POST['id']; $table = $POST['table']; //Check for existance if (!$id) die('You need to type in a session name.'); else { if (!$table) die('You need to re-enter you session name.'); } //Check for existance in Database mysql_select_db("reh_temp", $connect1); $q_id = mysql_query("SELECT * FROM users WHERE users='$id'"); if (mysql_num_rows($q_id)==0) { //Check Character Length if (strlen($id)<4||strlen($table)<4) die('Please enter a session name that is more than 4 characters.'); else { //Check for Match if ($id==$table) { //Insert value into users table mysql_select_db("reh_temp", $connect1); $q_id_reg = mysql_query("INSERT INTO users VALUES ('$id')"); mysql_select_db("reh_temp", $connect1); $session_table = "CREATE TABLE $table ( password varchar(10) )"; die ('Thanks!'); } else die ('Your session names do not match!'); } } else die ('The session name you choose is already in use. Please choose a different one.'); { ?> <head> <title>ReH-0.1--Create a Session</title> </head> <body bgcolor="#575757"> <center> <font color="#ffffff">Before encrypting your password, a session must be started. We need you to enter a personal session name that you will remember so that you password is protected by this session.</font><br><br> <form action="ReH-0.1.php" method="POST"> <input type="text" maxlength="10" size="10" name="id"><br> <font color="#ffffff">Please choose a session name.</font><br><br> <input type="text" maxlength="10" size="10" name="table"><br> <font color="#ffffff">Please re-enter you session name.</font><br><br> <input type="submit" value="Create Session"> </form> </center> </body> <?php } echo "I'm Working!"; ?> Any help and suggestions would help. Thanks! I've created both the scripts below. Which seem to work well on their own. The scripts are not interacting at the moment, however I do intend to use this lil $JSONloc (json encoded variable) from code 1, in Code 2. But they are not interacting atm. The Json variable is just a return from a database eg. "New York." and it returns whatever id I give it working fine. This map script = code 2: Will eventually plot a number of locations. Only 1 is set atm, but I've tested it with more, and it runs fine again on its own.
The problem is when I run both scripts together I get problems. In this case it echos the location fine but it doesn't load the map.
Ok so remove the echo statement... and then it says Page cannot be displayed
Ok so remove the PHP and the map works fine. Like WTH?
Do these things even work together? I'm at this 1 day and a half. Please help I've changed the personal details for security.
Code 1 <?php $ider = $_GET['id']; $host = "localhost"; $user = "user"; $password ="pass"; $database = "DB1"; mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // connect to mysql database try{ $connect = mysqli_connect($host, $user, $password, $database); } catch (mysqli_sql_exception $ex) { echo 'Error'; } $sql = "SELECT id, Location FROM Db1 WHERE id =$ider"; $result = $connect->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $thisloc = $row["Location"]; //get array data $JSONloc = json_encode($thisloc); //change to JSON echo $JSONloc; //test } } else { echo "0 results"; } $conn->close(); ?> Code 2 <!DOCTYPE html> <html> <head> <title>Custom Markers</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 90%; width: 70% margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map( document.getElementById('map'), {center: new google.maps.LatLng(64.009094, -7.316163), zoom: 13}); var iconBase = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/'; var iconBase2 = 'http://icons.iconarchive.com/icons/paomedia/small-n-flat/32/'; var icons = { // different icons for the map equipment: { icon: 'http://icons.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Marker-Outside-Azure-icon.png' }, library: { icon: iconBase2 + 'map-marker-icon.png' }, info: { icon: iconBase + 'info-i_maps.png' } }; var dormant = 'equipment'; var active = 'library'; var later = 64.013376; var longer = -7.307036; // static variables for testing var features = [ { position: new google.maps.LatLng(later, longer), type: active } ]; // Create markers. for (var i = 0; i < features.length; i++) { var marker = new google.maps.Marker({ position: features.position, icon: icons[features.type].icon, map: map }); }; } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=bla&callback=initMap"> </script> </body> </html> Edited February 26, 2020 by JonnyDriller Code: [Select] $url = 'http://gdata.youtube.com/feeds/api/playlists/blabla'; $fp = fopen($url, 'r'); $buffer=''; if ($fp) { while (!feof($fp)) $buffer .= fgets($fp, 1024); fclose($fp); $buff=stripslashes($buffer); $old = umask(0); file_put_contents("si.xml", $buff); chmod("si.xml", 0777); umask($old); The warnings I get are Code: [Select] Warning: file_put_contents(si.xml) [function.file-put-contents]: failed to open stream Warning: chmod() [function.chmod]: Permission denied I've even manually set entire directory file permissions to 777, but no use. Am using filezilla on windows Hi could anyone help me please. Hi I'm using an IP database to correctly (+/-) serve related ads based on country. This seems to work fine BUT when tested on a USA proxy (I'm in the UK) I am getting TWO ads served, one for USA (correctly) and one for the UK (proxy error?). When surfing via proxy from the Netherlands I get no image at all. Looking for somebody to see what I've done wrong he $server = 'localhost'; // MySQL hostname $username = '***'; // MySQL username $password = '***'; // MySQL password $dbname = '***'; // MySQL db name $db = mysql_connect($server, $username, $password) or die(mysql_error()); mysql_select_db($dbname) or die(mysql_error()); $sql = 'SELECT country FROM ip2nation WHERE ip < INET_ATON("'.$_SERVER['REMOTE_ADDR'].'") ORDER BY ip DESC LIMIT 0,1'; list($country) = mysql_fetch_row(mysql_query($sql)); switch ($country) { case 'us': // Image or USA echo '<img src="impact/samsungN210PLUS_usa.jpg">'; case 'uk': // Image for UK echo '<img src="impact/samsungN210PLUS_uk.jpg">'; default: // Image for everybody else (europe) echo '<img src="impact/samsungN210PLUS_europe.jpg">'; end; } echo '<div width="420" class="loc"><span class="loc" align="center">Not from '; $sql = 'SELECT c.country FROM ip2nationCountries c, ip2nation i WHERE i.ip < INET_ATON("'.$_SERVER['REMOTE_ADDR'].'") AND c.code = i.country ORDER BY i.ip DESC LIMIT 0,1'; list($countryName) = mysql_fetch_row(mysql_query($sql)); // Output full country name echo $countryName; $domain = str_replace("www.","", $_SERVER['HTTP_HOST']); echo '? Choose your flag: <a href="http://uk.' .$domain. '"><img src="images/flags/ukflag.gif"></a> <a href="http://usa.' .$domain. '"><img src="images/flags/usaflag.gif"></a> <a href="http://europe.' .$domain. '"><img src="images/flags/euflag.gif"></a></span></div>'; All help appreciated and thanks in advance. PS. The script is working he http://darrenbassett.com/trial if somebody in the USA wishes to check and let me kow if it is a proxy surfing error (seeing BOTH IP's). Not a real website just a 'play' page to get the bones of the script working. 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 Can anyone post a generic update function to update mysql table. The manual approach: update $tablename set $column1='a', $column2='b' where $id=$value; what Im basically trying to do is just like a phpmyadmin function... you select rows you want to update with a checkbox and then it takes you to a page where the rows that are clicked are shown in forms so that you can view and edit info in them... and then have 1 submit button to update them all at once. I'm new to PHP and I was able to figure out how to populate data from my database into my text fields. I am trying to add the update information to the same php file; however, I am now receiving errors within the data I was able to populate,
Notice: Undefined variable: stmt in C:\xampp\htdocs\Cust_App\update.php on line 47 and errors with the Update statement
Notice: Undefined variable: stmtupdate in C:\xampp\htdocs\Cust_App\update.php on line 96 I had defined the customerID variable above in the code, but it isn't being captured from here. I tried setting up this query like the one which gathered the data, but I'm off by a little bit. I would like the option to be able to update all fields. Any help is appreciated. I'm trying to learn as I may get asked to update other forms in the future. (new boss asks a lot) <?php require_once('database.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <!-- the head section --> <head> <title>My Guitar Shop</title> <link rel="stylesheet" type="text/css" href="main.css" /> </head> <!-- the body section --> <body> <div id="page"> <div id="header"> <h1>SportsPro Technical Support</h1> <p>Sports management software for the sports enthusiast.</p></h1> </div> <div id="main"> <h1>View/Update Customer</h1> <form action="update.php" method="get" > <?php if(isset($_GET['customerID'])) { $customerID = filter_input(INPUT_GET, 'customerID', FILTER_SANITIZE_NUMBER_INT); $sql = "SELECT * FROM customers WHERE customerID =$customerID "; $stmt = $db->query($sql); } ?> <div id="content"> <!-- display a table of products --> <h2>Customers</h2> <form method = "edit"> <?php foreach ($stmt as $cust) { ?> <div> <label>First Name</label> <input type="text" name="name" class ="form-control" value ="<?php echo $cust['firstName']; ?>"> </div><br> <div> <label>Last Name</label> <input type="text" name="name" class ="form-control" value ="<?php echo $cust['lastName']; ?>"> </div><br> <div> <label>Address</label> <input type="text" name="address" class ="form-control" value ="<?php echo $cust['address']; ?>"> </div><br> <div> <label>City</label> <input type="text" name="city" class ="form-control" value ="<?php echo $cust['city']; ?>"> </div><br> <div> <label>State</label> <input type="text" name="state" class ="form-control" value ="<?php echo $cust['state']; ?>"> </div><br> <div> <label>Country</label> <input type="text" name="countryCode" class ="form-control" value ="<?php echo $cust['countryCode']; ?>"> </div><br> <div> <label>Zip Code</label> <input type="text" name="postalCode" class ="form-control" value ="<?php echo $cust['postalCode']; ?>"> </div><br> <div> <label>Email </label> <input type="text" name="email" class ="form-control" value ="<?php echo $cust['email']; ?>"> </div><br> <div> <label>Phone Number </label> <input type="text" name="phone" class ="form-control" value ="<?php echo $cust['phone']; ?>"> </div><br> <div> <label>Password </label> <input type="text" name="password" class ="form-control" value ="<?php echo $cust['password']; ?>"> </div><br> <div> <?php } ?> <input type="Submit" name="Update_Data" value="Update Data"></input> <?php $sql2 = "UPDATE customers SET firstName = ". $stmtupdate['firstName']." WHERE customerID =$customerID "; $stmtupdate = $db->query($sql2); ?> </div> </div> <div id="footer"> <p> © <?php echo date("Y"); ?> SportsPro, Inc. </p> </div> </div><!-- end page --> </body> </html>
I created this code to upload a member's main picture on his member page on website. I'll only include the query part of the code since that's what is relevant to my problem. The idea is basically to upload a new picture onto the database if no picture already exists for that member and display the picture on the page. If a picture already exists, then the script replaces the old picture with the new one upon upload. But for whatever reason I don't understand, when I try to replace the old pic, it gets inserted in a new row on the database instead of replacing the old row, and the new pic gets displayed on the web page alongside the old. Code: [Select] $query = "SELECT username FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main'"; $result = @mysql_query($query); $num = @mysql_num_rows($result); if ($num> 0) { //Update the image $update = mysql_query("UPDATE images SET image = '" . $image['name'] . "' WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main'"); $_SESSION['error'] = "File updated successfully."; //really should be session success message. header("Location: member.php"); exit; } else { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into images (member_id, image_cartegory, image_date, image) values ('{$_SESSION['id']}', 'main', NOW(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); $_SESSION['error'] = "File uploaded succussfully."; //really should be session success message. header("Location: member.php"); } So can anyone tell me what the problem is? Could the fact that my insert script actually uploads the image onto a folder on my server and only stores the path name in the database have anything to contribute to the mixup? Appreciate your responses in advance. As the title says I need help with multiple update system.. Can't really get it to work at all >.< Here's some code: $selectt = mysql_query("SELECT * FROM exercises WHERE user='" . $_SESSION["user"] . "' AND exname='" . $_GET["edit"] . "'"); echo '<form method="POST" action="exercises.php?edited">'; echo '<div id="newexx">'; while($raw = mysql_fetch_array($selectt)) { echo '<input type="text" name="up[' . $raw["id"] . ']" value="' . $raw["swe"] . '">'; echo '<input type="text" name="up1[' . $raw["id"] . ']" value="' . $raw["eng"] . '"><br>'; echo '<input type="hidden" name="id[' . $raw["id"] . ']">'; } echo '</div>'; echo '<input type="submit" value="Update Exercise">'; echo '</form>'; if(isset($_GET["edited"])) { $swe = $_POST["up"]; $eng = $_POST["up1"]; $id = $_POST["id"]; foreach($id as $value => $index) { $update = "UPDATE exercises SET swe='".$swe."', eng='".$eng."' WHERE id='".$index."'"; mysql_query($update); } Would be thankful for reply! Good morning. I am looking fo some help with an update script to update all rows in a table. This is what I have for a form and all looks well. form.php <?php // run the query and put the results in an array variable called $result $result = mysql_query("SELECT * FROM table ORDER BY 'id', 'title', 'text', 'number'"); print "<form method='post' action='update.php'> <table width='100%' border='0' cellspacing='1' cellpadding='1'><tr> <td align='center'><strong>ID</strong></td> <td align='center'><strong>Title</strong></td> <td align='center'><strong>text</strong></td> <td align='center'><strong>Number</strong></td> </tr>\n"; // start a loop to print all of the courses with their book information // the mysql_fetch_array function puts each record into an array. each time it is called, it moves the array counter up until there are no more records left while ($Update = mysql_fetch_array($result)) { // start displaying the info; the most important part is to make the name an array (notice bookinfo[$i]) print "<td align='center'><p>{$Update['id']}</p></td>\n"; print "<td align='center'><input type='text' name='title' value='{$Update['title']}' /></td>"; print "<td align='center'><input type='text' size='40' name='text' value='{$Update['text']}' /></td>\n"; print "<td align='center'><input type='text' size='40' name='number' value='{$Update['number']}' /></td>\n"; print "</tr>\n"; // add 1 to the count, close the loop, close the form, and the mysql connection } print "<tr> <td colspan='4' align='center'><input type='submit' value='submit' />"; print "</td> </tr> </table> </td> </tr> </form> </table>"; print "</tr>\n"; ?><br /><br /> My question is. How do I update this info into the database with the proper info. ie. Update.php? Hi Guys, I want my UPDATE function from the code below to only update those fields that are NOT empty - if they are empty on submit then do not update or change any values from that field. I know that sounds odd, but with my file fields, when I submit to change something else at a later date it will overwrite the photo, download1,2 & 3 values and as a result I loose my files from the mysql table. Cheers, S <?php include('config.php'); if (isset($_GET['Ter']) ) { $ter = (int) $_GET['Ter']; if (isset($_POST['submitted'])) { //Photo & Document Upload Upload $timestamp_photo = time(); $timestamp_download1 = time(); $timestamp_download2 = time(); $timestamp_download3 = time(); //This is the directory where the files will be saved //Photos $photo_target = "images/"; $photo_target = $photo_target .$timestamp_photo. basename( $_FILES['photo']['name']); //Documents $download_target = "documents/"; $download_target1 = $download_target .$timestamp_download1. basename( $_FILES['download1']['name']); $download_target2 = $download_target .$timestamp_download2. basename( $_FILES['download2']['name']); $download_target3 = $download_target .$timestamp_download3. basename( $_FILES['download3']['name']); //This gets all the other information from the form $photo = ($_FILES['photo']['name']); $download1 = ($_FILES['download1']['name']); $download2 = ($_FILES['download2']['name']); $download3 = ($_FILES['download3']['name']); //Pause Photo/Document Upload foreach($_POST AS $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } $sql= "UPDATE `ter` SET `Ter` = '{$_POST['Ter']}' , `BranchName` = '{$_POST['BranchName']}' , `BranchAddress` = '{$_POST['BranchAddress']}' , `BranchTel` = '{$_POST['BranchTel']}' , `BranchEmail` = '{$_POST['BranchEmail']}' , `BranchLink` = '{$_POST['BranchLink']}' , `Theme` = '{$_POST['Theme']}' , `LocalInfo` = '{$_POST['LocalInfo']}' , `BranchInfo` = '{$_POST['BranchInfo']}' , `photo` = '$timestamp_photo{$_FILES['photo']['name']}' , `download1` = '$timestamp_download1{$_FILES['download1']['name']}' , `download1name` = '{$_POST['download1name']}' , `download2` = '$timestamp_download2{$_FILES['download2']['name']}' , `download2name` = '{$_POST['download2name']}' , `download3` = '$timestamp_download3{$_FILES['download3']['name']}' , `download3name` = '{$_POST['download3name']}' WHERE `Ter` = '$ter' "; mysql_query($sql) or die(mysql_error()); //Unpause Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $photo_target)) { echo "<br />The file ".$timestamp_photo. basename( $_FILES['photo']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download1']['tmp_name'], $download_target1)) { echo "<br />The file ".$timestamp_download1. basename( $_FILES['download1']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download2']['tmp_name'], $download_target2)) { echo "<br />The file ".$timestamp_download2. basename( $_FILES['download2']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload //Writes the photo to the server if(move_uploaded_file($_FILES['download3']['tmp_name'], $download_target3)) { echo "<br />The file ".$timestamp_download3. basename( $_FILES['download3']['name']). " has been uploaded. <br />"; } else { echo ""; } //End of Photo/Document Upload echo (mysql_affected_rows()) ? "<br />Edited Branch.<br />" : "<br />Nothing changed. <br />"; } $row = mysql_fetch_array ( mysql_query("SELECT * FROM `ter` WHERE `Ter` = '$ter' ")); ?> Hi, I found a couple of topics in the search on this but can't resolve my problem. I have a cart and want to mail it to myself and the client. The cart I'm using works fine but the moment I "check out" (mail the order) it gives a error. I build an error trap but see nothing wrong then I tried a different way to send the order in html with no avail. 6x files I use: Index.php -The products I'm selling and "add to chart" Cart.php - To update and display the products in the basket SendOrder.php - To mail the cart etc. to me and client as the main files and some functions, db connection and global's... 1) Index.php by Simon Mayer <?php // Start the session session_start(); // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>MedSET Store</title> <link rel="stylesheet" href="css/styles.css" > </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Products</h1> <?php $sql = 'SELECT * FROM books ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['title'].'" by '.$row['author'].': £'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); ?> </div> </body> </html> 2)Cart.php by Simon Mayer <?php // Start the session session_start(); // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } break; case 'delete': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } $_SESSION['cart'] = $cart; ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>MedSET Store</title> <link rel="stylesheet" href="css/styles.css" > </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="contents"> <h1>Please check quantities...</h1> <?php echo showCart(); ?> <form action="sendOrder.php" method="post"> //I added the action file to handle the form <input type="submit" name="sendmail" value="Check Out" > </form> <p><a href="index.php">Continue Shopping...</a></p> </div> </body> </html> 2.1)MySQL.class.php <?php /** * MySQL Database Connection Class * @access public * @package SPLIB */ class MySQL { /** * MySQL server hostname * @access private * @var string */ var $host; /** * MySQL username * @access private * @var string */ var $dbUser; /** * MySQL user's password * @access private * @var string */ var $dbPass; /** * Name of database to use * @access private * @var string */ var $dbName; /** * MySQL Resource link identifier stored here * @access private * @var string */ var $dbConn; /** * Stores error messages for connection errors * @access private * @var string */ var $connectError; /** * MySQL constructor * @param string host (MySQL server hostname) * @param string dbUser (MySQL User Name) * @param string dbPass (MySQL User Password) * @param string dbName (Database to select) * @access public */ function MySQL ($host,$dbUser,$dbPass,$dbName) { $this->host=$host; $this->dbUser=$dbUser; $this->dbPass=$dbPass; $this->dbName=$dbName; $this->connectToDb(); } /** * Establishes connection to MySQL and selects a database * @return void * @access private */ function connectToDb () { // Make connection to MySQL server if (!$this->dbConn = @mysql_connect($this->host, $this->dbUser, $this->dbPass)) { trigger_error('Could not connect to server'); $this->connectError=true; // Select database } else if ( !@mysql_select_db($this->dbName,$this->dbConn) ) { trigger_error('Could not select database'); $this->connectError=true; } } /** * Checks for MySQL errors * @return boolean * @access public */ function isError () { if ( $this->connectError ) return true; $error=mysql_error ($this->dbConn); if ( empty ($error) ) return false; else return true; } /** * Returns an instance of MySQLResult to fetch rows with * @param $sql string the database query to run * @return MySQLResult * @access public */ function query($sql) { if (!$queryResource=mysql_query($sql,$this->dbConn)) trigger_error ('Query failed: '.mysql_error($this->dbConn). ' SQL: '.$sql); return new MySQLResult($this,$queryResource); } } /** * MySQLResult Data Fetching Class * @access public * @package SPLIB */ class MySQLResult { /** * Instance of MySQL providing database connection * @access private * @var MySQL */ var $mysql; /** * Query resource * @access private * @var resource */ var $query; /** * MySQLResult constructor * @param object mysql (instance of MySQL class) * @param resource query (MySQL query resource) * @access public */ function MySQLResult(& $mysql,$query) { $this->mysql=& $mysql; $this->query=$query; } /** * Fetches a row from the result * @return array * @access public */ function fetch () { if ( $row=mysql_fetch_array($this->query,MYSQL_ASSOC) ) { return $row; } else if ( $this->size() > 0 ) { mysql_data_seek($this->query,0); return false; } else { return false; } } /** * Returns the number of rows selected * @return int * @access public */ function size () { return mysql_num_rows($this->query); } /** * Returns the ID of the last row inserted * @return int * @access public */ function insertID () { return mysql_insert_id($this->mysql->dbConn); } /** * Checks for MySQL errors * @return boolean * @access public */ function isError () { return $this->mysql->isError(); } } ?> 2.2)Global.inc.php <?php $host = 'localhost'; $user = 'MyUserName'; $pass = 'MyPassword'; $name = 'MyDataBase'; $db = &new MySQL($host,$user,$pass,$name); ?> 2.3)Function.inc.php <?php function writeShoppingCart() { $cart = $_SESSION['cart']; if (!$cart) { return '<p>You have no items in your shopping cart</p>'; } else { // Parse the cart session variable $items = explode(',',$cart); $s = (count($items) > 1) ? 's':''; return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>'; } } function showCart() { global $db; $cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; } $output[] = '<form action="cart.php?action=update" method="post" id="cart">'; $output[] = '<table>'; foreach ($contents as $id=>$qty) { $sql = 'SELECT * FROM books WHERE id = '.$id; $result = $db->query($sql); $row = $result->fetch(); extract($row); $output[] = '<tr>'; $output[] = '<td><a href="cart.php?action=delete&id='.$id.'" class="r">Remove</a></td>'; $output[] = '<td>'.$title.' by '.$author.'</td>'; $output[] = '<td>£'.$price.'</td>'; $output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>£'.($price * $qty).'</td>'; $total += $price * $qty; $output[] = '</tr>'; } $output[] = '</table>'; $output[] = '<p>Grand total: <strong>£'.$total.'</strong></p>'; $output[] = '<div><button type="submit">Update cart</button></div>'; $output[] = '</form>'; } else { $output[] = '<p>You shopping cart is empty.</p>'; } return join('',$output); } ?> 3)SendOrder.php <?php $cart = $_SESSION['cart']; $to = "me@myself.com"; $subject = "MedSET Order"; $message = "<html> <head> <title>Email Order<Title> </head> <body> This is my message in body </body>"; $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; $headers .= 'From: "email address" <an email existing on same server as shopping cart>' . "\r\n"; mail($to, $subject,$message,$headers,$cart); ?> Any help will be appreciated... Please help me with this: been doing this for 2 days and still cannot solve it. it won't update... I have attached my file: <?php include('connect-database.php'); if (isset($_POST['submit']) AND $_POST['submit'] == 'update') { $error = false; extract($_POST); if (empty($full_name)) $error = true; if (!$error) { $update = "UPDATE users SET full_name = '$full_name', WHERE id=$id "; mysql_query($update) or die(mysql_error() . "<br><br>" . $update); $full_name = ''; $message = "Record successfully updated."; } else { $message = "There is an error in your entry"; } } else { $id = intval(isset($_GET['id']) ? $_GET['id'] : 0); } if ($id == 0) { echo "<div style='margin-bottom:10px'>Invalid ID.</div>"; exit; } $query = "SELECT * FROM users WHERE id=$id"; $result = mysql_query($query) or die(mysql_error() . "<br><br>" . $query); if (mysql_num_rows($result) == 0) { echo "<div style='margin-bottom:10px'>Record Not Found in Database!</div>"; exit; } $row = mysql_fetch_array($result); extract($row); ?> <div id="mainContent" class="tab_container"> <div id="tab1" class="tab_content"> <h1>Edit Personal Data</h1> <div style="color:red;font-weight:bold"><? echo $message; ?></div> <form name="submit" action="" method="post"> <ul> <li><b>ID # :</b> <?php echo $id?></li> <li><b>Name :</b> <input type="text" name="full_name" id="" size="30" value="<?php echo $full_name ?>" /></li> <li><b>Address :</b> <input type="text" name="address" id="" size="55" maxlength="100" value="<?php echo $address ?>" /></li> <li><b>Contact Number :</b> <input type="text" name="contact_number" id="" size="11" value="<?php echo $contact_number ?>" /></li> <li><b>Email Address :</b> <input type="text" name="user_email" id="" size="30" value="<?php echo $user_email ?>" /></li> <li><b>Status :</b> <input type="text" name="status" id="" size="10" value="<?php echo $status ?>" /></li> <li><b>Nationality :</b> <input type="text" name="nationality" id="" size="20" value="<?php echo $nationality ?>" /></li> <li><b>Religion :</b> <input type="text" name="religion" id="" size="20" value="<?php echo $religion ?>" /></li> </ul> <h2>Self Description</h2> <p><textarea rows="9" cols="40" name="self_description" ><?php echo $self_description ?></textarea></p> <input type="hidden" name="id" value="<?php echo $id; ?>" /> <input type="submit" name="submit" value="update" /> </form> </div> Hi all, I have a script that is supposed to upload an image and then update a field in the table with the image's path in it. The image uploads okay but the details do not UPDATE in the table... any ideas? I have echoed after the sql statement which doesn't appear upon submitting but it shows the query printed out doing the right thing (I think) Quote UPDATE `fleet` SET `fleetimage4` = '../fleet/last.JPG' WHERE `fleetref` = '9' LIMIT 1 Code: [Select] <?php $ref = (!empty($_GET['ref']))?trim($_GET['ref']):""; $image = (!empty($_GET['image']))?trim($_GET['image']):""; $idir = "../fleet/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], "$idir" . $_FILES['fupload']['name']); // Move Image From Temporary Location To Permanent Location } } if (isset($_POST['submit'])){ //$fleetref=$_POST["fleetref"]; $fleetimage1 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $fleetimage2 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $fleetimage3 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $fleetimage4 = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); # setup SQL statement if ($image == "1") { $query = sprintf("UPDATE `fleet` SET `fleetimage1` = '$fleetimage1' WHERE `fleetref` = '$ref' LIMIT 1"); } else if ($image == "2"){ $query = sprintf("UPDATE `fleet` SET `fleetimage2` = '$fleetimage2' WHERE `fleetref` = '$ref' LIMIT 1"); } else if ($image == "3"){ $query = sprintf("UPDATE `fleet` SET `fleetimage3` = '$fleetimage3' WHERE `fleetref` = '$ref' LIMIT 1"); } else if ($image == "4"){ $query = sprintf("UPDATE `fleet` SET `fleetimage4` = '$fleetimage4' WHERE `fleetref` = '$ref' LIMIT 1"); } #execute SQL statement echo "before exe"; $result = mysql_db_query($db,$query,$cid) or die($query."<br>".mysql_error()); echo "after exe"; # check for error if (!$result){ echo("ERROR: " . mysql_error() . "\n$SQL\n"); }} ?> <div class="controls_left"> <FORM NAME="fa" ACTION="<?php echo "fleet_edit_image.php?ref=$ref&image=$image"; ?>" METHOD="POST" enctype="multipart/form-data"> <input type = "hidden" name="MAX_FILE_SIZE" value = "1000000"> Select image: <input type = "file" name = "fupload"> <p>Copyright note: Please only use photographs either that you have taken yourself or that you have permission to use as we will not be held responsible for any Copyright infringement.</p> <input name="submit" type="submit" value="Edit image" /> </FORM> </div> <div class="image_right"><?php if ($image == "1") { $imageprint = "$fleetimage1"; } else if ($image == "2") { $imageprint = "$fleetimage2"; } else if ($image == "3") { $imageprint = "$fleetimage3"; } else if ($image == "4") { $imageprint = "$fleetimage4"; } echo "<div class=\"image_right\"><img src=\"../$imageprint\" alt=\"Edit image\" width=\"293\" height=\"218\"></div>"; ?> So here is a concept of a permission system that I haven't really seen any where else. Now usually conventional permissions are usually stored in columns whilst the record specifies a bit which is then used to determine if the record has access to that permission.
Below is my concept of how permissions should be done, I'm looking for someone who can help me create the system in a way which would be easily implementable by other applications such as MyBB. In my case I have multiple game servers, and most of my players have accounts created on my forums which are powered by MyBB, I'm currently in the process of integrating their MyBB accounts across all my related game servers, but one thing I've noticed is that I have multiple permission systems created for all of my servers so right now I'm also trying to integrate all of them into one system so please try and understand that I designed this system in a way that could be used by multiple applications.
Any constructive criticism is accepted.
So the idea is that you have 1 table, I'll just list it here to make it easier to follow: - uniperms_nodes Now the uniperms_nodes table will contain the following columns: - key (Int, Not Null, Primary Key, Auto Increment) - type (Enum('USER', 'GROUP'), Not Null) - id (Int, Not Null) - permission (Varchar(255), Not Null) - description (Text)Now here is how it works, a record is inserted into the uniperms_nodes table containing the necessary information. Here is an example: INSERT INTO `uniperms_nodes` (`type`, `id`, `permission`, `description`) VALUES ('GROUP', '1', 'my.test.node', 'A simple permission'); With this information inserted, I can simply use the following query in order to get all of the permissions related to the GROUP with the ID of 1. SELECT `permission` FROM `uniperms_nodes` WHERE type='GROUP' AND id=1;With this array of permission nodes I can simply just check if the array has 'my.test.node', if the array contains 'my.test.node' then that means that the group I queried has access to that permission. Now the reason I have the types USER and GROUP is because maybe you would like to give permissions to individual users, but maybe you wouldn't necessarily want to create a new group. I'm currently looking for someone to help me create a lovely interface for this system, so that it's easier for the user to modify a group/user's permissions. If you're interested feel free to message me here on the forums or via email. kieron.wiltshire@outlook.com Edited by KieronWiltshire, 19 November 2014 - 11:15 AM. |