PHP - Editing/updating Data (php & Mysql)
Hello folks,
I can not seem to find out why this code is not being executed properly. Basically, I'd like to edit Records, so I am using forms to retrieve data, make modifications then save them. Code: [Select] <?php //connection to db $results = mysql_query("SELECT * FROM crud WHERE id=".$_GET[id]."") or die (mysql_error()); $row = mysql_fetch_assoc($results); echo "<form action=\"\" method=\"POST\">"; echo "Year: <input type=\"text\" value=".$row['car_year']." name=\"car_year\" /> <br />"; echo "Make: <input type=\"text\" value=".$row['car_make']." name=\"car_make\" /> <br />"; echo "Model: <input type=\"text\" value=".$row['car_model']." name=\"car_model\" /><br /><br />"; echo "Description:<br /><textarea rows=\"15\" cols=\"60\" name=\"description\" />". $row['description']. "</textarea>"; echo "<br /><input type=\"submit\" value=\"save\">"; echo "</form>"; if ($_POST['save']) { $car_year = $_POST['car_year']; $car_make = $_POST['car_make']; $car_model = $_POST['car_model']; $description = $_POST['description']; // Update data $update = mysql_query("UPDATE crud SET car_year='$car_year', car_make='$car_make' car_model='$car_model', description='$description' WHERE id=".$_GET['id']."") or die (mysql_error()); echo 'Update successfull'; } ?> Please HELP!!!! Similar TutorialsHello Im quite confused at what filtering I should use on my data when pulling it from a MySQL database. I don't sanitize my data on input because I am using prepared statements with PHP's PDO Driver which means I don't need to use mysql_real_escape_string() at all. When I pull the data to be displayed i.e. in a HTML Table I use the below function to make it safe for HTML output. public static function htmlSafe($data) { return nl2br(htmlentities($data, ENT_QUOTES)); } However the rules change when Im using a HTML Form to edit the data, and I am unsure what I need to strip out. I.e. What would I need to do to make all data safe to insert into the following form input. <input id = "someInput" type = "text" value = "<?php echo $someVarThatNeedsFiltering ?>" /> Also, one more question, in my html attributes (Valid ones like class, name, id, style, _target) I use a mixture of double quotes(") and single quotes ('), for quoting my values. Which one should I use or which one is more valid, doubles, or singles? I used to be good at this but I changed servers and everything is different... Heres my code so far: Code: [Select] <?php $rated=$_REQUEST['rated']; echo $rated; $rating=$_REQUEST['rating']; echo $rating; // Make a MySQL Connection mysql_connect("localhost", "********", "********") or die(mysql_error()); mysql_select_db("*********") or die(mysql_error()); $result = mysql_query("SELECT * FROM main WHERE username = '$rated'") or die(mysql_error()); $row = mysql_fetch_array( $result ); $votes = $db_field['$rating']; $newvotes = $votes + 1; echo $newvotes; mysql_query("UPDATE main SET $rating = '$newvotes' WHERE username = '$rated'"); ?> Whats going on here is the colomb that I want to update comes as a variable $rated (That works) and then the database selects the row to update with $username (That works) and gets the variable $newvotes by taking the original value of the data its about to update and add 1 to it (That works) Then it updates the field to $newvotes.... I don't know why the update won't go through... there are no errors.... Hi all I have 3 tables Table_1, Table_2 and Table_3 Table_1 is a list of countries, with name and country_id Table_2 is a table that has 3 fields, id, name and description Table 3 is a table that has name, Table_2_id So what I need to do: Display the name and description field of Table_2 in a form Loop through the countries table and display each as an input box and display on the same form When I fill out the form details, the name/description must be inserted into Table_2, creating an id The input boxes data then also needs inserting into Table_3, with the foreign key of Table_2_id So a small example would be: Name: testing Description: this is a test Country of Australia: Hello Country of Zimbabwe: Welcome This means that in Table_2, I will have the following: ============================= | id | name | description | 1 | testing | this is a test ============================= Table_3 ============================= | Table_2_id | name | country_id | 1 | Hello | 20 | 1 | Welcome | 17 ============================= 20 is the country_id of Australia 17 is the country_id of Zimbabwe Code: Generating the input fields dynamically: $site_id = $this->settings['site_id']; $options = ''; $country_code = ''; $query = $DB->query("SELECT country_code, country_id, IF(country_code = '".$country_code."', '', '') AS sel FROM Table_1 WHERE site_id='".$this->settings['site_id']."' ORDER BY country_name ASC"); foreach ($query->result as $row) { $options .= '<label>' . 'Test for ' . $this->settings['countries'][$row['country_code']] . '</label>' . '<br />'; //$row['country_id'] is the country_id from Table_1 $options .= '<input style="width: 100%; height: 5%;" id="country_data" type="text" name="' . $row['country_id'] . '" value="GET_VALUE_FROM_DB" />' . '<br /><br />'; } echo $options; This outputs: Code: [Select] Textareas go here...... <label>Test for Australia</label> <input type="text" value="" name="20" id="country_data" style="width: 100%; height: 5%;"> <label>Test for Zimbabwe</label> <input type="text" value="" name="17" id="country_data" style="width: 100%; height: 5%;"> Now, I need to insert the value of the input field and it's country_id (20 or 17) into Table_3 and also Table_2_id. This then means I could get the value from Table_3 to populate 'GET_VALUE_FROM_DB' But I'm at a loss on how I'd do this. Could someone help me with this? Thanks
I need help here. I am creating a system where the user will be able to update the product stock by uploading the stock of the products according to the id that has been assigned to the product.
I tried the code below but all i could not update my data into my database. And there's not error shown on my code. I do not know what is wrong with my codes. Please help me. <?php include 'conn.php'; if(isset($_POST["add_stock"])) { if($_FILES['product_file']['tmp_name']) { $filename = explode(".", $_FILES['product_file']['tmp_name']); if(end($filename) == "csv") { $handle = fopen($_FILES['product_file']['tmp_name'], "r"); while($data = fgetcsv($handle)) { $product_id = mysqli_real_escape_string($conn, $data[0]); $product_stock = mysqli_real_escape_string($conn, $data[1]); $product_status = 1 ; $query = "UPDATE products SET `product_stock` = '$product_stock', `product_status` = '$product_status' WHERE id = '$product_id'"; mysqli_query($conn, $query); } fclose($handle); header("location: upload-product.php?updation=1"); } else { echo '<script>alert("An error occur while uploading product. Please try again.") window.location.href = "upload-product.php"</script>'; } } else { echo '<script>alert("No file selected! ") window.location.href = "upload-product.php"</script>'; } } if(isset($_GET["updation"])) { echo '<script>alert("Product Stock Updated successfully!")</script>'; } ?> <div class="col-12"> <div class="card card-user"> <div class="card-header"> <h5 class="card-title">Update Product Stock</h5> <div class="card-body"> <div class="form-group"> <label for="file">Update Products stock File (.csv file)</label> <a href="assets/templates/product-template.xlsx" title="Download Sample File (Fill In Information and Export As CSV File)" class="mx-2"> <span class="iconify" data-icon="fa-solid:download" data-inline="false"> </a> </div> <form class = "form" action="" method="post" name="uploadCsv" enctype="multipart/form-data"> <div> <input type="file" name="product_file" accept=".csv"> <div class="row"> <div class="update ml-auto mr-auto"> <button type="submit" class="btn btn-primary btn-round" name="add_stock"> Import .cvs file</button> </div> </div> </div> </div> </form> </div> </div>
This is the template that i require user to key in and saved it in CSV format before uploading it. Hey guys, im new hear so im not shore how things work. Iv got a project where we are ment to alow users to record a bug fault in a computer, currently i have a page that looks like ths: <?php if (empty($_POST['bug_ID'])) echo "<p>You must enter a BUG ID number</p>"; else { $bugID = addslashes($_POST['bug_ID']); $name = addslashes($_POST['bug_name']); umask(0007); if (!file_exists("../../data/lab05")) mkdir("../../data/lab05", 02777); $lab05 = fopen("../../data/lab05/". "$bugID.txt", "a"); if (is_writable("../../data/lab05/NewBug.txt")) { if (fwrite($lab05, $bugID . ", " . $name . "\n")) echo "<p>Thank you entering a new bug</p>"; else echo "<p>Cannot add bug</p>"; } else echo "<p>Cannot write to the file.</p>"; fclose($lab05); } ?> this code runs fine however I also need to write a sperate page that allows for users to search and up date bugs recorded, I want them to search using the bug_ID field and we are ment to use the fgets method but am unshore, anyhelp would be much apricated. thank you I can add and delete data from my table. Now I need to be able to change one or more fields in an entry. So I want to retrieve a row from the db, display that data on a form where the user can change any field and then pass the changed data to an update.php program. I know how to go from form to php. But how do I pass the data from retrieve.php to a form so it will display? Do I use a URL and Get? Can I put the retrieve and form in the same program? I have , for example Col 1 Col 2 Col 3 I need to edit each record individually how Can I set this up I am new to php and am learning bits so any help will be appreciated Hello all, I am new to php coding and have a couple of problems with editing records in my database! I have two files below one test.php and edit.php. In the test.php the code outputs the records into a table. The problem is with the edit link as when it is selected I wish to be able to edit a record by a form, which is on edit.php. I am trying bring up the movie's information on the form to be edited. Currently on the form i get; Quote Movie: movie Gen Genre Year: year Any ideas how I can edit the record and then return to the test.php page? Code: [Select] test.php <html> <body style="background-color:#669999;"> <table width="490"border=0><tr> <td colspan="2" style="background-color:#FFA500;"> <div id="header" <h3 style="color:black">This is my first web-page! Below is a database of some of my favourite movies! </h3> </td> </tr> <?php //connecting to server $con = mysql_connect("localhost","root","NYOXAkly"); if (!$con) { die('could not connect: ' . mysql_error()); } //selecting movie database mysql_select_db("my_mov",$con); //Check if add button is active, start this if(isset($_REQUEST['add'])) { echo "<meta http-equiv=\"refresh\"content=\"0;URL=form.php\">"; } $result = mysql_query("SELECT * FROM Films ORDER BY filmID"); ?> <!-------------------------------creating table------------------------------------------------------------------------------------> <table width="490" border="0" cellspacing="1" cellpadding="0"> <tr> <td> <form name="test1" method="post" action="test.php"> <table width="490" border="10" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"><tr> <td bgcolor="#FFFFFF"></td> <td align="center" colspan="6" bgcolor="#FFFFFF">Movie Database</td></tr> <td align="center" bgcolor="#FFFFFF">filmID</td> <td align="center" bgcolor="#FFFFFF">Movie</td> <td align="center" bgcolor="#FFFFFF">Genre</td> <td align="center" bgcolor="#FFFFFF">Year</td> <td align="center" bgcolor="#FFFFFF">Edit</td> <td align="center" bgcolor="#FFFFFF">Delete</td> </tr> <?php while($rows=mysql_fetch_array($result)) { ?> <tr> </td> <td bgcolor="#FFFFFF"><? echo $rows['filmID']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['movie']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['genre']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['year']; ?></td> <td bgcolor="#FFFFFF"> <a href="edit.php?filmID=<?php echo 'filmID';?>">Edit</a> <td bgcolor="#FFFFFF"> <a href="delete.php?filmID=<?php echo 'filmID';?>">Delete</a> </td> </tr> <?php } echo print_r(error_get_last()); mysql_close(); ?> <!--add button--> <tr> <td colspan="15" align="left" bgcolor="#FFFFFF"> <input name='add' type="submit" filmID="add" value="Add A New Record" action="form.php?"> </td> </tr> </table> </form> <br/> By C.M.D.W <br/> <?php echo date("Y/m/d") . "<br />"; ?> </body> </html> Code: [Select] edit.php <html> <body style="background-color:#669999;"> <!------------------Creates a form ----------------------> <br /> <form action="" method="post"> <fieldset> <legend>Enter your movies into database here!</legend> Movie: <input type ="text" name="movie" value="<?php echo 'movie';?>"> <br /> Gen <input type ="text" name="genre" value="<?php echo 'genre';?>"/> <br /> Year: <input type ="text" name="year" value="<?php echo 'year';?>"/> <br /> <input type="submit" name="name" value="Submit" /> </fieldset> </form> <?php //connecting to server $con = mysql_connect("localhost","root","NYOXAkly"); if (!$con) { die('could not connect: ' . mysql_error()); } //selecting movie database mysql_select_db("my_mov",$con); if (isset($_POST['submit'])) { // confirm that the 'id' value is a valid integer if (is_numeric($_POST['filmID'])) // get form data $filmID = $_POST['filmID']; $movie = mysql_real_escape_string(htmlspecialchars($_POST['movie'])); $genre = mysql_real_escape_string(htmlspecialchars($_POST['genre'])); $year = mysql_real_escape_string(htmlspecialchars($_POST['year'])); // check that fields are filled in if ($movie == '' || $genre == '' || $year == '') { // generate error message $error = 'ERROR: Please fill in all required fields!'; } else { // save the data to the database } mysql_query("UPDATE players SET movie='$movie', genre='$genre', year='$year' WHERE filmID='$filmID'") or die(mysql_error()); // once saved, redirect back to the view page header("Location: test.php"); } } if (isset($_GET['filmID']) && is_numeric($_GET['filmID']) && $_GET['filmID'] > 0) { // query db $id = $_GET['filmID']; $result = mysql_query("SELECT * FROM Films WHERE filmID=$FilmID") or die(mysql_error()); $row = mysql_fetch_array($result); // check that the 'id' matches up with a row in the databse if($row) { // get data from db $movie = $row['movie']; $genre = $row['genre']; $year = $row['year']; }} ?> <br/> <br/> <a href="test.php">Return To Home Page</a> <br/> <br/> By C.M.D.W <br/> <?php echo date("Y/m/d") . "<br />"; ?> </body> </html> Thanks Chris Hi guys, just wondering if someone can help me i am currently trying to edit a MYSQL database through PHP and just wondering if you could take a look at the code i have and tell me where i have gone wrong. I have tried to use a tutorial but have got lost and need some help. This is for my final year project for University and really needs to be done soon so i would be really greatful if someone could help me out. Thanks code below: Code: [Select] <!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"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <link rel="stylesheet" type="text/css" href="style.css"/> <title>Database Editor</title> </head> <body> <div id="page"> <img src="images/banner1.jpg" alt="banner"/> <div id="navi-container"> <ul id="navi"> <li><a href="index.php">Home</a></li> <li><a href="news.php">News</a></li> <li><a href="latest_products.php">Latest Products</a></li> <li><a href="gallery.php">Gallery</a></li> <li><a href="Admin_page.php">Administration</a></li> </ul> </div> <?php ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <h1>Database Editor</h1> <table class="inputtable"> <tr> <td class="label">Item Name:</td> <td class="inputtd"> <input name="Item_Name" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label"> Item Image:</td> <td class="inputtd"> <input name="Item_Image" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label">Item Description:</td> <td class="inputtd"> <input name="Item_Description" type="text" class="standardwidth" /></td> </tr> <tr> <td class="label">Item Number:</td> <td class="inputtd"> <input name="Item_Number" type="text" class="standardwidth" /></td> </tr> </table> <br /> <table class="radbuttons"> <tr> <td class="standardwidth"> <input name="op" type="radio" checked="checked" value="rdbase" /> Read from Database</td> <td><input name="op" type="radio" value="cdbase" />Change Entry (enter data in form)</td> </tr> <tr> <td class="standardwidth"> <input name="op" type="radio" value="adbase" />Add to Database</td> <td><input name="op" type="radio" value="ddbase" />Delete Entry (enter name in form)</td> </tr> </table> <br /> <input name="submit" type="submit" value="submit" /> <input name="reset" type="reset" value="reset" /> <br /> </form> <?php if (count($view->peopleList) > 0) { ?> <table class="datatable"> <tr> <th><strong>Surname</strong></th> <th><strong>First Name </strong></th> <th class="standardwidth"><strong>Address </strong></th> <th><strong>Phone</strong></th> </tr> <?php foreach ($view->peopleList as $person) : ?> <tr> <td> <?php echo $person->getSurname(); ?> </td> <td> <?php echo $person->getFirstname(); ?> </td> <td> <?php echo $person->getAddress(); ?> </td> <td> <?php echo $person->getPhone(); ?> </td> </tr> <?php endforeach; } ?> </table> <?php ?> <?php $dbc = mysql_connect ('****','***','salford*****') OR die('Could not connect to MySQL : ' . mysql_error() ); mysql_select_db ('****') OR die('Could not select the database : ' . mysql_error() ); $query = "SELECT * FROM ****** ORDER BY Item_Number"; $result = mysql_query ($query); ?> <body> <h1>Database</h1> <table border="1"> <tbody> <tr> <td>Item Name</td> <td>Item Image</td> <td>Item Description</td> <td>Item Number</td> </tr> <?php while($row = mysql_fetch_array($result,MYSQL_ASSOC)) { echo " <tr> <td>$row[Item_Name]</td> <td>$row[Item_Image]</td> <td>$row[Item_Description]</td> <td>$row[Item_Number]</td> </tr> "; } mysql_close(); ?> $sql = 'INSERT INTO murrayfp10_ipad (Item_Name, Item_Description, Item_Number) VALUES (:Item_Name, :Item_Description, :Item_Number)'; $result = $this->dbh->prepare($sql); $result->execute(array( ':Item_Name' => $data['Item_Name'], ':Item_Description' => $data['Item_Description'], ':Item_Number' => $data['Item_Number'] )); return $this->dbh->lastInsertId(); } public function edittbl($data) { $sql = 'UPDATE murrayfp10_ipad SET Item_Name = :Item_Name, Item_Description = :Item_Description, Item_Number = :Item_Number WHERE Item_Name = :Item_Name'; $result = $this->dbh->prepare($sql); return $result->execute(array( ':Item_Name' => $data['Item_Name'], ':Item_Description' => $data['Item_Description'], ':Item_Number' => $data['Item_Number'], ':Item_Number' => $data['Item_Number'] )); } public function deletetbl($data) { $sql = 'DELETE FROM murrayfp10_ipad WHERE Item_Name = :Item_Name'; $result = $this->dbh->prepare($sql); return $result->execute(array( ':Item_Name' => $data['Item_Name'] )); } <div style="text-align:center;"> Copyright © M.Murray 2011 </div> </body> </html> Hey there is no error with this code it works just fine but I would love to know if there is unnecessary coding in it for example do i have to do the global variables? is there a better way to do mysql editing page? thanks <?php include "../configdb.php"; $id = $_GET['id']; if(isset($_POST['submit'])) { //global variables $name = $_POST['name']; $footer = $_POST['footer']; //run the query which adds the data gathered from the form into the database $result = mysql_query("UPDATE pages SET name='$name', footer='$footer' WHERE id='$id' ",$connect); echo "<b>Your Page have been edited successfully"; } elseif($id) { $result = mysql_query("SELECT * FROM pages WHERE id='$id' ",$connect); while($row = mysql_fetch_assoc($result)) { $name = $row['name']; $footer = $row['footer']; ?> <h3>::Edit Page</h3> <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>?id=<?php echo $row['id']?>"> <input type="hidden" name="id" value="<?php echo $row['id']?>"> <input name="name" size="40" maxlength="255" value="<?php echo $name; ?>"> <input name="footer" size="40" maxlength="255" value="<?php echo $footer; ?>"> <input type="submit" name="submit" value="Submit"> <?php } } Hello. I hope someone out there can help me with this as I have been trying all different ways to make this work but to no avail. I have a report.php page that allows a user to search 3 particular fields in a database to retrieve search results that displays itself on the same page. What I am looking to do is have both an EDIT and DELETE button/link for each queried result that is retrieved allowing the user to edit or delete the search result of their choice. Or, how to implement some inline editing on the results that are retrieved by the search query. Here is the code I have so far with the EDIT or DELETE options feature that I am wanting to utilize. Code: [Select] <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Budgets Report</title> </head> <body class="oneColFixCtr"> <div id="container"> <h2>Budget Report</h2> <form name="search" method="post" style="background-color:#FFF" action="<?php $PHP_SELF?>"> <span id="search">Search for</span>: <input type="text" name="find" /> in <Select NAME="field"> <Option VALUE="rundate">rundate</option> <Option VALUE="section">section</option> <Option VALUE="reporter">reporter</option> </Select> <input type="hidden" name="searching" value="yes" /> <input type="submit" name="search" value="Search" /> </form> <?php // check to see if anything is posted if (isset($_POST['find'])) {$find = $_POST['find'];} if (isset($_POST['searching'])) {$searching = $_POST['searching'];} if (isset($_POST['field'])) {$field = $_POST['field'];} //This is only displayed if they have submitted the form if (isset($searching) && $searching=="yes") { echo "<h2>Results</h2><p>"; // If they did not enter a search term we give them an error if (empty($find)) { echo "<p>You forgot to enter a search term"; exit; } // Otherwise we connect to our Database mysql_connect("localhost", "root", "root") or die(mysql_error()); mysql_select_db("budgets") or die(mysql_error()); // We preform a bit of filtering $find = strtoupper($find); $find = strip_tags($find); $find = trim ($find); // Now we search for our search term, in the field the user specified $data = mysql_query("SELECT * FROM daily_budget WHERE upper($field) LIKE'%$find%' ORDER BY section ASC"); // And we display the results while($result = mysql_fetch_array( $data )) { echo "<strong>Section:$nbsp</strong>"; echo " ";echo $result['section']; echo "<br>"; echo $result['slug']; echo " "; echo ":"; echo " "; echo $result['budgetInfo']; echo " "; echo "/"; echo " "; echo $result['reporter']; echo " "; echo $result['notes']; echo " "; echo $result['art_photos']; echo " "; echo $result['artDesc']; echo " "; echo $result['multimedia']; echo " "; echo $result['multimediaDesc']; echo "<br>"; echo "Pickup"; echo " "; echo ":"; echo " "; echo $result['pickup']; echo "<br>"; echo "Sidebar"; echo " "; echo ":"; echo " "; echo $result['sidebar']; echo "<br> "; echo $result['sSlug']; echo " "; echo $result['sBudget']; echo " "; echo $result['sArt']; echo " "; echo "EDIT"; echo " "; echo "| "; echo " ";echo "DELETE"; echo " "; echo "<br>"; echo "<hr>"; } //This counts the number or results - and if there wasn't any it gives them a little message explaining that $anymatches=mysql_num_rows($data); if ($anymatches == 0) { echo "Sorry, but we can not find an entry to match your query<br><br>"; } //And we remind them what they searched for echo "<b>Searched For:</b> " .$find; } ?> </div> </div> </body> </html> Hey Guys, Here is my issue. I have a MySQL database with a table of products. I use this table to generate a mutliselect form element that is used int a larger form. The larger form contains other information relevant to an issue that we are having with that product (such as an outage). Anyway, the form works fine and the form validation works fine and I write it to the database fine. The issue I'm having is how to save the mutliselect options most efficiently. This is my current process: 1. User creates a new entry from the form and clicks save 2. The form is validated 3. All entries are written to the database in a table called "incidents" (content inclues, timestamps, description of the problem, the impact, who to contact, etc) 4. Because the products list can vary from 1 product to all (~30) products I broke it out into a separate table called "impacted_products". I then loop through each of the selected products and write one row for each product using the id from the row in the "incidents" table to define the tables relationship. Example of DB results: "incidents" +-----------------+------+----------+---------------------+---------+---------+ | notification_id | what | impact | time_start | summary | contact | +-----------------+------+----------+---------------------+---------+---------+ | 235235 | Test | None.... | 2011-02-08 13:41:00 | Test | 3 | +-----------------+------+----------+---------------------+---------+---------+ "impacted_products" +-----+-----------------+------------+---------------------+---------+ | id | notification_id | product_id | timestamp | deleted | +-----+-----------------+------------+---------------------+---------+ | 202 | 235235 | 7 | 2011-02-10 14:30:42 | 0 | | 203 | 235235 | 37 | 2011-02-10 14:30:42 | 0 | | 204 | 235235 | 23 | 2011-02-10 14:30:42 | 0 | +-----+-----------------+------------+---------------------+---------+ 5. Now the users wants to go back and make some updates. 6. They click the edit button from the menu on screen and the form is brought back up and all options/fields are filled out from that which is stored in the database. 7. They make their edits and save again. 8. Now this time it simple updates the "incidents" table but for the products table I do a: "UPDATE impacted_products SET deleted=1 WHERE notification_id='$ID'" and "delete" all the old impacted_products for this particular incident and then loop through all the products that the user still had selected and write them to the database again. 9. And repeat So as you can see this could end up with a lot of "useless" entries in the database since my scripts only pay attention to those "impacted_products" whose deleted value is set to 0. Example: +-----+-----------------+------------+---------------------+---------+ | id | notification_id | product_id | timestamp | deleted | +-----+-----------------+------------+---------------------+---------+ | 176 | 235235 | 37 | 2011-02-08 15:26:25 | 1 | | 177 | 235235 | 43 | 2011-02-08 15:26:25 | 1 | | 178 | 235235 | 37 | 2011-02-08 15:37:58 | 1 | | 179 | 235235 | 43 | 2011-02-08 15:37:58 | 1 | | 180 | 235235 | 1 | 2011-02-08 15:39:49 | 1 | | 181 | 235235 | 7 | 2011-02-08 15:39:49 | 1 | | 182 | 235235 | 37 | 2011-02-08 15:39:49 | 1 | | 183 | 235235 | 43 | 2011-02-08 15:39:49 | 1 | | 184 | 235235 | 1 | 2011-02-08 15:40:53 | 1 | | 185 | 235235 | 7 | 2011-02-08 15:40:53 | 1 | | 186 | 235235 | 37 | 2011-02-08 15:40:53 | 1 | | 187 | 235235 | 43 | 2011-02-08 15:40:53 | 1 | | 188 | 235235 | 37 | 2011-02-10 10:00:47 | 1 | | 189 | 235235 | 1 | 2011-02-10 12:17:05 | 1 | | 190 | 235235 | 7 | 2011-02-10 12:17:05 | 1 | | 191 | 235235 | 13 | 2011-02-10 12:17:05 | 1 | | 192 | 235235 | 37 | 2011-02-10 12:17:05 | 1 | | 193 | 235235 | 23 | 2011-02-10 12:17:05 | 1 | | 194 | 235235 | 1 | 2011-02-10 12:21:52 | 1 | | 195 | 235235 | 7 | 2011-02-10 12:21:52 | 1 | | 196 | 235235 | 13 | 2011-02-10 12:21:52 | 1 | | 197 | 235235 | 37 | 2011-02-10 12:21:52 | 1 | | 198 | 235235 | 23 | 2011-02-10 12:21:52 | 1 | | 199 | 235235 | 7 | 2011-02-10 12:22:26 | 1 | | 200 | 235235 | 37 | 2011-02-10 12:22:26 | 1 | | 201 | 235235 | 23 | 2011-02-10 12:22:26 | 1 | | 202 | 235235 | 7 | 2011-02-10 14:30:42 | 0 | | 203 | 235235 | 37 | 2011-02-10 14:30:42 | 0 | | 204 | 235235 | 23 | 2011-02-10 14:30:42 | 0 | +-----+-----------------+------------+---------------------+---------+ I did it this way beacuase it seems the easiest and fastest way. Otherwise I would have to lookup all the impacted_products from the table that match that notification_id and check 1) Was there a new product selected? If so, add it. 2) Was a product that was selected no longer selected? If so, delete it. 3) Was a product that was selected before still selected now? If so, leave it alone. This seemed like a lot of extra looping and a lot of extra DB queries to essentially end up at the same place. However, I feel that there has still got to be a more efficient way of doing this where I won't have all the extra entries in the impacted_products table. Any ideas? Thanks in advance! Ok, so I'm not quite sure how to explain this, but here it goes: I have table A that contains stats for all players in the NHL, and then I have table B with just a few players. These few players in table B are also in table A, but table B has more information on them. I want to take the stats for these players out of table A and put into table B, and I want table B to update along with table A every time those numbers change. How would I do this? Hi, I want to loop out data from DB in <input> and change and update several posts at the same time. Can you give me a short example, how <input> and maybe foreach could look like? Thanks I am working on a php project in which players can equipt items from there inventory and it shows them there current stats. When players have decided to equipt an item they hit the submit button and the new stats should show. The issue I have is that the data is delaying in update such as: we have 10 strength we equipt a sword with +2 to strength and click submit it displays we have 10 strength we equipt a axe with +3 to strength and click submit it displays 12 strength we equipt a sword with +2 to strength and click submit it displays 13 strength we equipt a sword with +2 to strength and click submit it displays 12 strength .... my code is represented below <?php updateEquiptment(); require("playerInfo.php"); ?> <p title="This stat increases how hard you hit with weapons!">Strength:<?php echo $baseStrength + getModStrength() ?> </p> the functions updateEquiptment and getModStrength are in the playerInfo.php file and are shown like this: $user = $_SESSION['username']; $result = mysql_fetch_row(mysql_query("SELECT equiptment FROM warUsers WHERE name = '$user'")); $equiptment = explode(",",$result[0]); function updateEquiptment() { global $user; $result = mysql_fetch_row(mysql_query("SELECT equiptment FROM warUsers WHERE name = '$user'")) or die(mysql_error()); global $equiptment; $equiptment = explode(",",$result[0]); } //get there modified stats function getModStrength() { $total = 0; global $equiptment; foreach ($equiptment as $value) //loop through every item in the equiptment { if($value == 0 || $value == null) //if nothing is equipt go to the next loop continue; $result = mysql_query("SELECT * FROM items WHERE id = '$value'"); $item = mysql_fetch_row($result); $total += $item[4]; //get the items strength and add it to the total } return $total; } any help on the matter would be greatly appreciated Hey guys, I got another one that i could use some help on. I have a input form that utilizes a javascript that adds additional rows to my table. here is a look at what i got. Code: [Select] <script type="text/javascript"> function insertRow() { var x = document.getElementById('results_table').insertRow(-1); var a = x.insertCell(0); var b = x.insertCell(1); var c = x.insertCell(2); var d = x.insertCell(3); var e = x.insertCell(4); a.innerHTML="<input type=\"text\" name=\"id\">"; b.innerHTML="<input type=\"text\" name=\"place\">"; c.innerHTML="<input type=\"text\" name=\"username\">"; d.innerHTML="<input type=\"text\" name=\"earnings\">"; e.innerHTML="<input type=\"button\" value=\"delete\" onClick=\"deleteRow(this)\">"; } function deleteRow(r) { var i=r.parentNode.parentNode.rowIndex; document.getElementById('results_table').deleteRow(i); } </script> this is my code stored in the header of my page. basically just a button to add a new row and a button in each row to delete rows if needed. here is a look at my html table, pretty basic... Code: [Select] <table id="results_table"> <th>Event ID</th><th>Place</th><th>Username</th><th>Earnings</th> <tr> <td><input type="text" name="id"></td><td><input type="text" name="place"></td><td><input type="text" name="username"></td><td><input type="text" name="earnings"></td><td><input type="button" value="delete" onClick="deleteRow(this)"</td> </tr> </table> Now what I am hoping to acheive is once i submit all of these rows to the database i will insert each of these rows into their own row in the database. is this doable? the structure of my database is: ResultID (Primary Key) Place Earnings UserID (Foreign Key) EventID (Foreign Key) now i think the biggest problem i'm having with submitting data to the database is that in the original HTML form I am typing in the actual username and not the userID. so when it comes to processing I need to do a switch of these two things before I run my query. Should something like this work? Code: [Select] $username = $_POST['username']; $userID = "SELECT userID FROM users WHERE username="$username"; $query = mysql_query($userID); also i've never tried to submit multiple entries at a time. maybe i have to create an array somehow in order to capture each rows data. any thoughts? as always thanks for the help. Hello all, I have form that has several fields. Each field will be saved to a table (which is a relations table we will call markups). The form is built from another table which is an array of categories. The output will build a form with each category and allow the end-user to input data for each category. The information the user will be entering is markup values. Cat1 | Markup Input Cat2 | Markup Input Cat3 | Markup Input I'll be saving the data in their own columns and not as an serialized array to the database. I'm currently looping through the arrayed fields and saving the data to the markup relations table. I've read other forums and serializing the data will be to difficult to retrieve for relationship purposes?? Anyway, here's my question: Let's say the user is entering the markups for the first time. They go down the list of categories and add their markups for each and click save. Cool, no problem just do an INSERT INTO. Then, they go into the category setup screen and add a category then go back to the markup screen and now have to update the category markup that was just added. So now I have to do an UPDATE to the current listed markups table (no problem). But now I have to add another row in the same table from that array. Is there a logical way of handling this. I guess I'm looking for some ideas on how to accomplish this task. I hope you guy understand what I'm after here. Thanks for any suggestions on this. hi, Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\Sahansevena_ver1\admin\profile\updAdmiInfo.php on line 49 i got this error. here is the coding Code: [Select] <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ $dbuser="root"; $dbpswd="****"; $dbserver="localhost"; $nwuser=$_POST['username']; $c_pw=$_POST['cur_password']; $n_pw=$_POST['conf_password']; //$user=$userName; //$pass=$password; // $dbname="sahansevena"; if($_SERVER['REQUEST_METHOD']=='POST'){ //get username and password from admin login.php $con=mysql_connect($dbserver,$dbuser,$dbpswd); if(!$con){ die('coudnt connect db connection prob'.mysql_error()); }else{ if($c_pw==$n_pw){ $uname=mysql_real_escape_string($username); $pword=mysql_real_escape_string($n_pw); // setDatabase($dbname, $con) ; mysql_select_db($dbname, $con); // $result="update admin set username='$uname',password='$pword'" where limit 0; $result="update admin set username='$uname' , password='$pword', last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname' limit 0"; //Checked to see if any rows were returned from the database // If rows were returned, set a session variable to 1 $result=mysql_query($result); if ($result) { $numRow=mysql_numrows($result); if($numRow>0){ //session_start(); //SESSION['admin']="menuka"; echo "data was suaccesfully updated"; /// header ("Location:config/menu.php"); //mysql_close($con); }else{ //session_start(); echo " problem in updating "; //$_SESSION['login'] = ""; //header ("Location:login.php"); } } else { trigger_error(mysql_error(), E_USER_ERROR); } } } }else{ echo 'error message not post methode'; include(login.php); } ?> please check my code and help me to figur out the error thanks in advance, menukadevinda 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. |