PHP - Mysql Updating Row To Blank Value
Hey guys, I have a private message script but for some reason when its updating, it turns the value into a blank one from 1 to 3.
I have no idea why, but it works with the old statement of deleting, but I changed it to instead update it to 3 because I want to keep the pm in archives. here is the delete PM part. <?php session_start(); header("Location:inbox.php"); $user = $_SESSION['username']; include 'db.php'; //We do not have a user check on this page, because it seems silly to, you just send data to this page then it directs you right back to inbox //We need to get the total number of private messages the user has $sql = mysql_query ("SELECT pm_count FROM users WHERE username='$user'"); $row = mysql_fetch_array ($sql); $pm_count = $row['pm_count']; //A foreach loop for each pm in the array, get the values and set it as $pm_id because they were the ones selected for deletion foreach($_POST['pms'] as $num => $pm_id) { //Delete the PM from the database mysql_query("UPDATE messages SET recieved='3' WHERE id='$pm_id' AND reciever='$user'"); // mysql_query("DELETE FROM messages WHERE id='$pm_id' AND reciever='$user'"); //Subtract a private message from the counter! YAY! //$pm_count = $pm_count - '1'; //Now update the users message count with the new value //mysql_query("UPDATE users SET pm_count='$pm_count' WHERE username='$user'"); } ?> The commented out part at the end, is the old deleting parts but instead changed it to update value. Here is my form that shows checkboxes. I showed the whole code, where it has comments. <?php //This stuff and the while loop will query the database, see if you have messages or not, and display them if you do $query = "SELECT id, sender, subject, message FROM messages WHERE reciever='$user' AND recieved='1'"; $sqlinbox = mysql_query($query); //We have a mysql error, we should probably let somone know about the error, so we should print the error if(!$sqlinbox) { ?> <p><?php print '$query: '.$query.mysql_error();?></p> <?php } //There are no rows found for the user that is logged in, so that either means they have no messages or something broke, lets assume them they have no messages elseif (!mysql_num_rows($sqlinbox) ) { ?> <center><p><b>You havent read any messages</b></p></center> <?php } //There are no errors, and they do have messages, lets query the database and get the information after we make a table to put the information into else { //Ok, Lets center this whole table Im going to make just because I like it like that //Then we create a table 80% the total width, with 3 columns, The subject is 75% of the whole table, the sender is 120 pixels (should be plenty) and the select checkboxes only get 25 pixels ?> <center> <form name="send" method="post" action="delete.php"> <table width="80%"> <tr> <td width="75%" valign="top"><p><b><u>Subject</u></b></p></td> <td width="120px" valign="top"><p><b><u>Sender</u></b></p></td> <td width="25px" valign="top"><p><b><u>Select</u></b></p></td> </tr> <?php //Since everything is good so far and we earlier did a query to get all the message information we need to display the information. //This while loop goes through the array outputting all of the message information while($inbox = mysql_fetch_array($sqlinbox)) { //These are the variables we get from the array as it is going through the messages, we have the id of the private message, we have the person who sent the message, we have the subject of the message, and yeah thats it $pm_id = $inbox['id']; $sender = $inbox['sender']; $subject = $inbox['subject']; //So lets show the subject and make that a link to the view message page, we will send the message id through the URL to the view message page so the message can be displayed //And also let the person see who sent it to them, if you want you can make that some sort of a link to view more stuff about the user, but Im not doing that here, I did it for my game though, similar to the viewmsg.php page but a different page, and with the senders id //And finally the checkboxes that are all stuck into an array and if they are selected we stick the private message id into the array //I will only let my users have a maximum of 50 messages, remeber that ok? Because that's the value I will later in another page //Here is finally the html output for the message data, the while loop keeps going untill it runs out of messages ?> <tr> <td width="75%" valign="top"><p><a href="viewmsg.php?msg_id=<?php echo $pm_id; ?>"><?php echo $subject; ?></a></p></td> <td width="120px" valign="top"><p><?php echo $sender; ?></p></td> <td width="25px" valign="top"><input name="pms[]" type="checkbox" value="<?php echo $pm_id; ?>"></td> </tr> <?php //This ends the while loop } //Here is a submit button for the form that sends the delete page the message ids in an array ?> <tr> <td colspan="3"><input type="submit" name="Submit" value="Delete Selected"></td> <td></td> <td></td> </tr> </table> </center> <?php //So this ends the else to see if it is all ok and having messages or not } ?> So yeah, does anyone know why it updates it to a blank value, from the value 1 in recieved? Similar TutorialsI must be using the wrong search terms in google cause I cant find out how to update a field to a blank spot. trying to make name blank. I thought it was just " " hope someone can please help me with this Code: [Select] mysql_query("UPDATE users SET name = '".mysql_real_escape_string "."' WHERE id = '".mysql_real_escape_string($_SESSION['user_id']))."'"; Hello there. I have a small form the inputs a new message into the column 'status'. But when I insert the new text, it deletes whatever is already in the column and leaves it blank. It will never add the new text to the column. Here is the form: $status_sql=mysql_query("SELECT status FROM global"); $status_data=mysql_fetch_assoc($status_sql); echo '<br /><br />Current Status Message: '.$status_data['status'].'<br />'; echo '<form name="status" method="post" action="?page=panel&action=sdo"><input type="text" class="console" name="status"> <input type="submit" class="cbutton" value="Enter"></form>'; $status = mysql_real_escape_string($_POST['status']); $update=mysql_query("UPDATE global SET status='$status' WHERE id='1'") or die('Query: ' . $update . '<br />Failed with: ' . mysql_error()); echo '<br />Status changed to: '.$status.''; If you need more info, just let me know. Thank you a million! I have a form that allows my client to update some products. Now the products are simple just basic info and 1 picture. I have set this up so they can edit the products and change the information, having done this many times in the past, but now hit a puzzling block that I am baffled. The client when editing is presented with the form with the information pulled from the database and the form fields loaded with that data ready to edit. The image can either be left alone or they can choose to upload a new image. They are shown the image they currently have stored in the database. The problem I have is EVEN if they decide not to upload an image and change other information, when the submit the form it must be sending a blank value for the image somewhere as it is updating the database and removing the image reference as if it has been removed. I have an if/else statement based on the form to perform 2 different queries for the update in mysql. Here is the code for the form update, as you can see the image should not update?? Please help?? if ($_SERVER['REQUEST_METHOD'] =='POST') { //This stops SQL Injection in POST vars foreach ($_POST as $key => $value) { $_POST[$key] = mysql_real_escape_string($value); } // **************************** THIS IS FOR NO NEW IMAGE ******************************** if ($_SERVER['REQUEST_METHOD'] =='POST' && empty($_FILES['product_image']['name'])) { # setup SQL statement for no new image $SQL = " UPDATE products SET product_title = '{$_POST['product_title']}', product_description = '{$_POST['product_description']}', standard_price = '{$_POST['standard_price']}', deluxe_price = '{$_POST['deluxe_price']}' WHERE product_id = '{$_REQUEST['product_id']}' "; } // **************************** THIS IS FOR A NEW IMAGE ******************************** else { // Check the image type is a jpeg or gif for the image. if (($_FILES['product_image']['type'] != "image/gif") && ($_FILES['product_image']['type'] != "image/jpeg") && ($_FILES['product_image']['type'] != "image/pjpeg")) { echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\">You have chosen not to upload a <b>Product Image</b>.<BR></SPAN>" ; } elseif ($_FILES['product_image']['size'] > 100000) { echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\">The file size is bigger than 300kb.<BR></SPAN>" ; } else { move_uploaded_file($_FILES['product_image']['tmp_name'], "/httpdocs/product_images/".$_FILES['product_image']['name']) ; echo "<FONT FACE=\"Verdana\"><SPAN CLASS=\"content\"><B>Your front image has successfully uploaded.</B><BR></SPAN>" ; } } # setup SQL statement for update $SQL = " UPDATE products SET product_title = '{$_POST['product_title']}', product_description = '{$_POST['product_description']}', standard_price = '{$_POST['standard_price']}', deluxe_price = '{$_POST['deluxe_price']}', product_image = '{$_FILES['product_image']['name']}' WHERE product_id = '{$_REQUEST['product_id']}' "; } #execute SQL statement $result = mysql_db_query( *****,"$SQL",$connection ); # check for error if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } <?php $PostID = mysql_escape_string($_GET['postid']); ?> <?php If ($_GET['CODE'] == '0') { $GetPostData = "SELECT * FROM ".FORUM_POSTS." WHERE post_id='{$PostID}'"; $GetPostRes = mysql_query($GetPostData, $db); $PostText = mysql_result($GetPostRes, 0, 'post_text'); $AuthorID = mysql_result($GetPostRes, 0, 'user_id'); If ($memid == $AuthorID || $MemLevel >= 1000) { ?> <div class="maintitle" align="left"><img src="./images/nav_m.gif" width="8" height="8"> Editing Post</div> <form action="index.php?act=edit&postid=<?php echo $PostID; ?>&CODE=1" method="POST"> <table width="100%" cellspacing="1" cellpadding="4"> <tr> <td class="titlemedium" colspan="2">Make changes below.</td> </tr> <tr> <td class="row2" align="right" width="15%" valign="top">Post Text:</td> <td class="row2" align="left" width="85%"> <textarea cols="80" rows="20" name="posttext"><?php echo $PostText; ?></textarea> </td> </tr> <tr><td class="row2" colspan="2" align="center"><input type="submit" value="Post" /></td></tr> </table> </form> <?php } Else { ?> <div class="maintitle" align="left"><img src="./images/nav_m.gif" width="8" height="8"> Error</div> <table width="100%" cellspacing="1" cellpadding="4"> <tr><td class="row2">You do not have the permission to edit this post.<br>If you believe this is an error please contact an administrator.</td></tr> </table> <?php } } If ($_GET['CODE'] == '1') { //Gather Information $PostText = mysql_escape_string($_POST['posttext']); $PostText = htmlentities($PostText); $PostID = mysql_escape_string($_GET['postid']); //Update Database $EditQry = "UPDATE ".FORUM_POSTS." SET post_text='{$PostText}' WHERE post_id='{$PostID}'"; $EditRes = mysql_query($EditQry, $db); //Check Data went in If (!$EditRes) { ?> <div class="maintitle" align="left"><img src="./images/nav_m.gif" width="8" height="8"> Error</div> <table width="100%" cellspacing="1" cellpadding="4"> <tr><td class="row2">Could not modify database. Please contact administrator.</td></tr> </table> <?php } Else { ?> <div class="maintitle" align="left"><img src="./images/nav_m.gif" width="8" height="8"> Success</div> <table width="100%" cellspacing="1" cellpadding="4"> <tr><td class="row2">Post modified. Please go back to the thread to see it.</td></tr> </table> <?php } } ?> </div> This is my page for editing a post. However, whenever this form actually goes through, the query for some reason makes post_text in the database blank with no text in it whatsoever. I have tried echoing the query to see what it says and it has a perfectly fine query and I can copy/paste it manually to put it into the mysql but I don't get why this isn't adding it. Shouldn't the following stop a blank row from being inserted into mysql? I have a description and a date but it still keeps putting a blank row before my insert and I've tried everything.... if($myvar != ''){ mysql_query("INSERT IGNORE INTO products (description, time) VALUES('$myvar',NOW() ) ") or die(mysql_error()); Hi
I have another problem with my code
I have records in my database and i want to put them in Jgrid but no records are show.
This is my php
<?php error_reporting(0); require_once 'database_connection.php'; $page = $_GET['page']; // get the requested page $limit = $_GET['rows']; // get how many rows we want to have into the grid $sidx = $_GET['sidx']; // get index row - i.e. user click to sort $sord = $_GET['sord']; // get the direction if(!$sidx) $sidx =1; // connect to the database $result = mysql_query("SELECT COUNT(*) AS count FROM utilizador"); $row = mysql_fetch_array($result,MYSQL_ASSOC); $count = $row['count']; if( $count >0 ) { $total_pages = ceil($count/$limit); } else { $total_pages = 0; } if ($page > $total_pages) $page=$total_pages; $start = $limit*$page - $limit; // do not put $limit*($page - 1) $SQL = "SELECT * FROM utilizador ORDER BY $sidx $sord LIMIT $start , $limit"; $result = mysql_query( $SQL ) or die("Couldn t execute query.".mysql_error()); $responce->page = $page; $responce->total = $total_pages; $responce->records = $count; $i=0; while($row = mysql_fetch_array($result,MYSQL_ASSOC)) { $responce->rows[$i]['id']=$row[idutilizador]; $responce->rows[$i]['cell']=array($row[idutilizador],$row[nome],$row[utilizador],$row[telefone],$row[email]); $i++; } echo json_encode($responce); ?>And this is the Jgrid <html> <head> <title>jQGrid example</title> <!-- Load CSS--><br /> <link rel="stylesheet" href="css/ui.jqgrid.css" type="text/css" media="all" /> <!-- For this theme, download your own from link above, and place it at css folder --> <link rel="stylesheet" href="css/jquery-ui-1.9.2.custom.css" type="text/css" media="all" /> <!-- Load Javascript --> <script src="js/jquery_1.5.2.js" type="text/javascript"></script> <script src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script> <script src="js/i18n/grid.locale-pt.js" type="text/javascript"></script> <script src="js/jquery.jqGrid.min.js" type="text/javascript"></script> </head> <body> <table id="datagrid"></table> <div id="navGrid"></div> <p><script language="javascript"> jQuery("#datagrid").jqGrid({ url:'example.php', datatype: "json", colNames:['Idutilizador','Nome', 'Utilizador', 'Telefone','Email'], colModel:[ {name:'idutilizador',index:'idutilizador', width:55,editable:false,editoptions:{readonly:true,size:10}}, {name:'nome',index:'nome', width:80,editable:true,editoptions:{size:10}}, {name:'idutilizador',index:'idutilizador', width:90,editable:true,editoptions:{size:25}}, {name:'telefone',index:'telefone', width:60, align:"right",editable:true,editoptions:{size:10}}, {name:'email',index:'email', width:60, align:"right",editable:true,editoptions:{size:10}} ], rowNum:10, rowList:[10,15,20,25,30,35,40], pager: '#navGrid', sortname: 'idutilizador', sortorder: "asc", height: 500, width:900, viewrecords: true, caption:"Atividades Registadas" }); jQuery("#datagrid").jqGrid('navGrid','#navGrid',{edit:true,add:true,del:true}); </script> </body> </html>Anything wrong with the code? Regards Hi, Does anyone have any experience of using PHP to transfer data from an XML file to a MySQL database? For the last 5 weeks I have been trying to get the following code to work but I am still unable to do it. The code does copy the file from my root folder into another (I eventually plan to use external download onto my server). However, it comes up with the following error: "Cannot instantiate non-existent class: xmlreader in" which refers to this: $xmlReader = new XMLReader(); Does anyone have any experience of transferring data from an XML file to a database? I am using PHP 5 so I dont know why this doesn't work. <?php ini_set('display_errors', 1); error_reporting(-1); $host="hostname"; // $username="username"; // $password="password"; // $db_name="db"; // $tbl_name="productfeed"; // // Connect to server and select database. mysql_connect("$host", "$username", "$password")or ("no connection"); mysql_select_db("$db_name")or die("Database Connection Error"); $xmlReader = new XMLReader(); $filename = "datafeed_98057.xml"; $url = "[url=http://www.ukhomefurniture.co.uk/datafeed.xml]http://www.ukhomefurniture.co.uk/datafeed.xml[/url]"; file_put_contents($filename, file_get_contents($url)); $xmlReader->open($filename); while ($xmlReader->read()) { switch ($xmlReader->name) { case'prod': $dom = new DOMDocument(); $domNode = $xmlReader->expand(); $element = $dom->appendChild($domNode); $domString = utf8_encode($dom->saveXML($element)); $product = new SimpleXMLElement($domString); $product_code = $product->prod['id']; $image = $product->awImage; //insert query if(strlen($product) > 0) { $query = mysql_query("REPLACE INTO productfeed (image) VALUES ('$awImage')"); echo $awImage . "has been inserted </br>"; die('yes it works'); error_reporting(E_ALL); if (ini_get('display_errors')) { ini_set('display_errors', 1); } } break; } } ?> MOD EDIT: DB credentials removed. Hi, 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 there, I am using this code to send the users email address to the database. That works fine, but i keep getting blank info added to the database. Does anyone know how i can stop this? <?php $con = mysql_connect("*","*","*"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ogs_mailinglist1", $con); $sql="INSERT INTO mailinglist (email) VALUES ('$_POST[rec_email]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); ?> Thanks, How can I store data which is in a email to a MySQL db? Currently I'm receiving all enquirers in to my INBOX. I need a way to upload data which is in the mail direct from my email page to a MySQL db. is this possible? or what's the best way to approach this? Hi All, Whenever I try to update any piece of PHP code to update a MySQL database, nothing happens. I have tried copying in some of the working codes of a website and tried the same, but no success. I recently installed XAMPP. I am connecting using the correct user id and pass to the database. The scripts are not giving me any error, but just not connecting, that's all. While making such a usage as noted below <FORM name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" > I get the following error Firefox can't find the file at /C:/xampp/htdocs/="<?php.. so on Why does this happen? I am pretty new to this, so please do help. Thanks, Satheesh P R Hi, when someone logs in to my page, i have a form displayed with names, address, etc...what i need to do is when i hit the update button for that information to go into the MYSQL table I have created and over write that information if a user updates...so how do i do that? is it possible to update data in mysql when a user clicks logout? Hello, I've been tasked with updating our code base from mysql to something that will work with php 7. It's older code that was written by 2 or 3 individuals before me and it's not at all object oriented. There are about 540 different files that I will end up having to edit to make it all up to date. I'm not a very experienced programmer myself, and I'm in need of some guidance. There are some files that have functions that call and use mysql queries three or four files deep and going through and editing one function leads me to having to update 4 or 5 other files which breaks stuff somewhere else down the road. I was wondering if anyone has some suggestions on ways to make this process less painful. The other thing is that by using PDO in a not OO style, it seems like I'm losing a lot of its benefits. Should I consider using MYSQLi instead of PDO considering the circumstances? Are there any resources that you could point me to in order to help me learn the skills I need to make it through this upgrade? Thanks for the help! 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!!!! the below code as I understand should insert a new record into my database, but it's not. <?php $notes = $_POST['notes']; $cnamedb = $_POST['cname']; $username = $_SESSION['username']; mysql_query("INSERT INTO `ccccomma_eve`.`corps` (`id`, `name`, `ticker`, `alliance`, `ceo`, `tax`, `members`, `hq`, `apidate`, `notes`, `notedate`, `updatedby`) VALUES ('', '$cnamedb', '', '', '', '', '', '', '', '$notes', NOW(), '$username'"); echo $cnamedb." Updated"; ?> Any ideas why? For the last few days I have been trying to work out why my code does not update the MySQL database table. Having tried several variation I have the below but cannot see anything wrong. The rest of the program produces the correct results (displaying what is currently on the table) showing it is connecting to the correct table but altering the table is not working. Any help greatly appreciated. The few lines in question a Code: [Select] // Update the profile data in the database if (!$error) { if (!empty($name)&& !empty($phone) && !empty($address1) && !empty($address2)) { // Only set the picture column if there is a new picture if (!empty($new_picture)) { //if (!empty($postcode)){ $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', picture = '$new_picture', username = '" . $_SESSION['username'] . "' WHERE name = '" . $row['name'] ."'"; }} else { $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', username = '" . $_SESSION['username'] . "' WHERE name = '" . $row['name'] ."'"; } mysqli_query($dbc, $query) or die("<br>Query $query<br>Failed with error: " . mysqli_error($dbc) . '<br>On line: ' . __LINE__); The whole program is below Code: [Select] <?php error_reporting(E_ALL); session_start(); ?> <?php require_once('appvars.php'); require_once('connectvars1.php'); // Connect to the database $dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name); if (!isset($_GET['user_id'])) { $query = "SELECT * FROM antique WHERE user_id = '" . $_SESSION['user_id'] . "'"; } else { $query = "SELECT * FROM antique WHERE user_id = '" . $_GET['user_id'] . "'"; } $data = mysqli_query($dbc, $query); if (mysqli_num_rows($data) == 1) { // The user row was found so display the user data $row = mysqli_fetch_array($data); echo '<table>'; if (!empty($row['name'])) { echo '<tr><td class="label">Name:</td><td>' . $row['name'] . '</td></tr>'; } if (!empty($row['phone'])) { echo '<tr><td class="label">Phone:</td><td>' . $row['phone'] . ' </td></tr>'; } if (!empty($row['address1'])) { echo '<tr><td class="label">Address1:</td><td>' . $row['address1'] . ' </td></tr>'; } if (!empty($row['address2'])) { echo '<tr><td class="label">Address2:</td><td>' . $row['address2'] . ' </td></tr>'; } if (!empty($row['postcode'])) { echo '<tr><td class="label">Postcode:</td><td>' . $row['postcode'] . ' </td></tr>'; } if (!empty($row['webadd'])) { echo '<tr><td class="label">Web address:</td><td>' . $row['webadd'] . ' </td></tr>'; } if (!empty($row['email'])) { echo '<tr><td class="label">Email:</td><td>' . $row['email'] . ' </td></tr>'; } if (!empty($row['username'])) { echo '<tr><td class="label">Username:</td><td>' . $row['username'] . ' </td></tr>'; } if (!empty($row['user_id'])) { echo '<tr><td class="label">User ID:</td><td>' . $row['user_id'] . ' </td></tr>'; } echo '</table>'; //echo '<class = "label">USER ID: ' . $_SESSION['user_id'] . ''; if (!isset($_GET['postcode']) || ($_SESSION['postcode'] == $_GET['postcode'])) { echo '<p>Would you like to <a href="index5.php">Go to Homepage</a>?</p>'; } } // End of check for a single row of user results else { echo '<p class="error">There was a bit of a problem accessing your profile.</p>'; } ?> <hr> <?php require_once('appvars.php'); require_once('connectvars1.php'); // Make sure the user is logged in before going any further. if (!isset($_SESSION['user_id'])) { echo '<p class="login">Please <a href="login1.php">log in</a> to access this page.</p>'; exit(); } // Connect to the database $dbc = mysqli_connect(DB_Host, DB_User, DB_Password, DB_Name); if (isset($_POST['submit'])) { // Grab the profile data from the POST $name = mysqli_real_escape_string($dbc, trim($_POST['name'])); $phone = mysqli_real_escape_string($dbc, trim($_POST['phone'])); $address1 = mysqli_real_escape_string($dbc, trim($_POST['address1'])); $address2 = mysqli_real_escape_string($dbc, trim($_POST['address2'])); $postcode = mysqli_real_escape_string($dbc, trim($_POST['postcode'])); $webadd = mysqli_real_escape_string($dbc, trim($_POST['webadd'])); $email = mysqli_real_escape_string($dbc, trim($_POST['email'])); $old_picture = mysqli_real_escape_string($dbc, trim($_POST['old_picture'])); $new_picture = mysqli_real_escape_string($dbc, trim($_FILES['new_picture']['name'])); $new_picture_type = $_FILES['new_picture']['type']; $new_picture_size = $_FILES['new_picture']['size']; $username = mysqli_real_escape_string($dbc, trim($_POST['username'])); $user_id = mysqli_real_escape_string($dbc, trim($_POST['user_id'])); if (!empty($_FILES['new_picture']['tmp_name'])) {list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']); } //list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']); $error = false; // Validate and move the uploaded picture file, if necessary if (!empty($new_picture)) { if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') || ($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) && ($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) { if ($_FILES['new_picture']['error'] == 0) { // Move the file to the target upload folder $target = MM_UPLOADPATH . basename($new_picture); if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) { // The new picture file move was successful, now make sure any old picture is deleted if (!empty($old_picture) && ($old_picture != $new_picture)) { } } else { // The new picture file move failed, so delete the temporary file and set the error flag @unlink($_FILES['new_picture']['tmp_name']); $error = true; echo '<p class="error">Sorry, there was a problem uploading your picture.</p>'; } } } else { // The new picture file is not valid, so delete the temporary file and set the error flag @unlink($_FILES['new_picture']['tmp_name']); $error = true; echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) . ' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>'; } } $error = false; // Update the profile data in the database if (!$error) { if (!empty($name)&& !empty($phone) && !empty($address1) && !empty($address2)) { // Only set the picture column if there is a new picture if (!empty($new_picture)) { //if (!empty($postcode)){ $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', picture = '$new_picture', username = '" . $_SESSION['username'] . "' WHERE name = '" . $row['name'] ."'"; }} else { $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', username = '" . $_SESSION['username'] . "' WHERE name = '" . $row['name'] ."'"; } mysqli_query($dbc, $query) or die("<br>Query $query<br>Failed with error: " . mysqli_error($dbc) . '<br>On line: ' . __LINE__); // Confirm success with the user echo '<p>Your profile has been successfully updated. Would you like to <a href="viewprofile4.php">view your profile</a>?</p>'; mysqli_close($dbc); exit(); } else { echo '<p class="error">You must enter all of the profile data (the picture is optional).</p>'; } } // End of check for form submission else { // Grab the profile data from the database $query="SELECT * FROM antique WHERE user_id= '" . $row['user_id'] . "'"; $data = mysqli_query($dbc, $query); $row = mysqli_fetch_array($data); if ($row != NULL) { $name = $row['name']; $phone = $row['phone']; $address1 = $row['address1']; $address2 = $row['address2']; $postcode = $row['postcode']; $email = $row['email']; $webadd = $row['webadd']; $old_picture = $row['picture']; $username = $_SESSION['username']; $user_id = $row['user_id']; } else { echo '<p class="error">There was a problem accessing your profile.</p>'; } } mysqli_close($dbc); ?> <form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MM_MAXFILESIZE; ?>" /> <fieldset> <legend>Personal Information</legend> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br /> <label for="phone">Phone:</label> <input type="text" id="phone" name="phone" value="<?php if (!empty($phone)) echo $phone; ?>" /><br /> <label for="address1">Address1:</label> <input type="text" id="address1" name="address1" value="<?php if (!empty($address1)) echo $address1; ?>" /><br /> <label for="address2">Address2:</label> <input type="text" id="address2" name="address2" value="<?php if (!empty($address2)) echo $address2; ?>" /><br /> <label for="postcode">Postcode:</label> <input type="text" id="postcode" name="postcode" value="<?php if (!empty($postcode)) echo $postcode; ?>" /><br /> <label for="email">Email:</label> <input type="text" id="email" name="email" value="<?php if (!empty($email)) { echo $email; } else { echo 'No email entered';} ?>" /><br /> <label for="webadd">Web address:</label> <input type="text" id="webadd" name="webadd" value="<?php if (!empty($webadd)) { echo $webadd; } else { echo 'No web address entered';} ?>" /><br /> <input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" /> <label for="new_picture">Pictu </label> <input type="file" id="new_picture" name="new_picture" /> <?php if (!empty($old_picture)) { echo '<img class="profile" src="' . MM_UPLOADPATH . $old_picture . '" alt="Profile Picture" style: height=100px;" />'; } ?> <br /> <label for="username">Username:</label> <input type="text" id="username" name="username" value="<?php if (!empty($username)) echo $username; ?>" /><br /> <label for="user_id">User ID:</label> <input type="text" id="user_id" name="user_id" value="<?php echo '' . $row['user_id'] . '' ; ?>" /><br /> </fieldset> <input type="submit" value="Save Profile" name="submit" /> </form> <?php echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. <a href="logout3.php">Log out</a>.</p>'); echo '<class = "label">USER ID: ' . $row['user_id'] . ''; ?> <p><a href="index.php">Return to homepage</a></p> <?php require_once('footer.php'); ?> </body> </html> I have the following code, (I'm sorry it's so long an it does more that the question asks.) It's ment to edit, delete and make new links in a mysql database, by also using a link header to home all the links (Like a dropdown menu) And thig manages the links. However then the update, or when the new form is submitted it leaves then titlereg field blank. (The titlereg is the id of the main link, it's called reg in the title_reg database) I know this is complicated and i'm not too good at explaining the problem but any help would be great. I have commented on anything that could help. <?php include "../includes/mysql_connect.php"; include "../includes/info_files.php"; echo "<strong>Links</strong><br />"; echo "Currect links:<br /><br />"; if($_POST['submit']){ $name = mysql_real_escape_string($_POST['name']); $titlereg = mysql_real_escape_string($_POST['titlereg']); $url = mysql_real_escape_string($_POST['url']); $id = mysql_real_escape_string($_POST['id']); mysql_query("UPDATE nav_sub SET name='$name', SET titlereg='$titlereg', SET url='$url' WHERE reg='$id'"); ////////////////////////////////// Here will help, the update MY SQL thingie echo "Link Changed.<br /><br />"; } elseif($_POST['remove']){ $id = mysql_real_escape_string($_POST['id']); mysql_query("DELETE FROM nav_sub WHERE reg='$id'"); echo "Link deleted.<br /><br />"; } else{ $result = mysql_query("SELECT * FROM nav_sub"); while($row = mysql_fetch_array($result)) { echo '<strong>' . $row['name'] . '</strong>'; echo '<form action="" method="post">'; echo 'Name: <input type="text" name="name" value="' . $row['name'] . '" /><br />'; echo 'Link: <input type="text" name="text" value="' . $row['url'] . '" /><br />'; echo 'Navigation title: <select name="titlereg">'; $resultabc = mysql_query("SELECT * FROM nav_title"); while($rowabc = mysql_fetch_array($resultabc)) { echo '<option value="' . $rowabc['reg'] . '">' . $rowabc['name'] . '</option>'; ////////////////////////////////// Here is the option } echo '</select>'; echo '<input type="hidden" name="id" value="' . $row['reg'] . '" />'; echo '<input type="submit" name="submit" value="Change" /> <input type="submit" name="remove" value="Remove" /><br />'; echo '</form>'; } } echo "New link:<br /><br />"; if($_POST['new_submit']){ ////////////////////////////////// Here!!!!!!!!!!!!!!! $result = mysql_query("SELECT * FROM nav_sub"); $new_titlereg = $_POST['new_titlereg']; $new_name = mysql_real_escape_string($_POST['new_name']); $new_url = mysql_real_escape_string($_POST['new_url']); mysql_query("INSERT INTO `nav_sub` (`titlereg` ,`reg` ,`name` ,`url`)VALUES ('$new_titlereg', '', '$new_name', '$new_url')"); ////////////////////////////////// here is the MY SQL statement... echo "Link added.<br /><br />"; } echo '<form action="" method="post">'; echo 'Name: <input type="text" name="new_name" value="" /><br />'; echo 'Url: <input type="text" name="new_url" value="" /> \\\\ If your linking to a page you made, then the url is index.php?catt=(The categrory you put)&page=(The page you put)<br />'; echo 'Navigation title: <select name="new_titlereg">'; $resultab = mysql_query("SELECT * FROM nav_title"); while($rowab = mysql_fetch_array($resultab)) { echo '<option value="' . $rowab['reg'] . '">' . $rowab['name'] . '</option>'; ////////////////////////////////// Here isn't submitting the value in the option } echo '</select>'; echo '<input type="submit" name="new_submit" value="Insert" /><br />'; echo '</form>'; ?> By the way, explain simply as I'm only 13 I am trying to update multiple rows in a mysql db through php but I am getting an error message in this line: $size = count($_POST['uid']); My db field names are uid (which autoincrements and does not need to be updated), fname, lname and email fields. Here is a link for the project I need to develophttp://users.cis.fiu.edu/~vagelis/classes/COP5725/project.htm Here is the content for the first page: 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> <style type="text/css"> body { margin:50px 0px; padding:0px; text-align:center; font:13px Tahoma,Geneva,sans-serif } #content { width:1000px; margin:0px auto; text-align:left; padding:15px; border:1px dashed #333; background-color:#eee; } </style> <link rel="icon" href="http://www.mysite.com/favicon.ico" type="image/vnd.microsoft.icon" /> </head> <body> <div id='content'><h3><center>Update Information</center></h3> <?php //create a connection $connection = mysql_connect("localhost","root","r2d2c3po"); //test the connection if (!$connection) { die("Database connection failed: " . mysql_error()); } //select database to use mysql_select_db("music_social_network", $connection); //setup query $sql = "SELECT * FROM `user` ORDER BY uid"; //get results from query or die $result = mysql_query($sql, $connection) or die(mysql_error()); //fetch rows from query $rows = mysql_fetch_assoc($result); ?> <?php // find out how many records there are to update $size = count($_POST['uid']); // start a counter in order to number the input fields for each record $i = 0; print "<table width='100%' border='0' cellspacing='1' cellpadding='0'><tr><td>"; // open a form print "<form name='namestoupdate' method='post' action='update.php'> <table width='100%' border='0' cellspacing='1' cellpadding='1'><tr> <td align='center'><strong>User ID</strong></td> <td align='center'><strong>First Name</strong></td> <td align='center'><strong>Last Name</strong></td> <td align='center'><strong>Email</strong></td> </tr>\n"; // start a loop to print all of the users with their 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)) { print "</tr>\n"; // assuming you have three important columns (the index (id), the course name (course), and the book info (bookinfo)) // start displaying the info; the most important part is to make the name an array (notice bookinfo[$i]) print "<td align='center'><p>{$Update['uid']}</p></td>\n"; print "<td align='center'><input type='text' fname='fname[$i]' value='{$Update['fname']}' /></td>"; print "<td align='center'><input type='text' size='40' lname='lname[$i]' value='{$Update['lname']}' /></td>\n"; print "<td align='center'><input type='text' size='40' email='email[$i]' value='{$Update['email']}' /></td>\n"; print "</tr>\n"; // add 1 to the count, close the loop, close the form, and the mysql connection ++$i; } print "<tr> <td colspan='4' align='center'><input type='submit' value='submit' />"; print "</td> </tr> </table> </td> </tr> </form> </table>"; mysql_close($connection); ?><br /><br /><div></body> </html> here is the content for the update.php page: <!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> <style type="text/css"> body { margin:50px 0px; padding:0px; text-align:center; font:13px Tahoma,Geneva,sans-serif } #content { width:1000px; margin:0px auto; text-align:left; padding:15px; border:1px dashed #333; background-color:#eee; } </style> <link rel="icon" href="http://www.mysite.com/favicon.ico" type="image/vnd.microsoft.icon" /> </head> <body> <div id='content'><h3><center>Success! </center></h3> <table width='100%' border='0' cellspacing='1' cellpadding='0'><tr><td> <table width='100%' border='0' cellspacing='1' cellpadding='1'> <tr> <td align='center'><strong>User ID</strong></td> <td align='center'><strong>First Name</strong></td> <td align='center'><strong>Last Name</strong></td> <td align='center'><strong>Email</strong></td> </tr> <?php //create a connection $connection = mysql_connect("localhost","root","r2d2c3po"); //test the connection if (!$connection) { die("Database connection failed: " . mysql_error()); } //select database to use mysql_select_db("music_social_network", $connection); //setup query $sql = "SELECT * FROM `user` ORDER BY uid"; //get results from query or die $result = mysql_query($sql, $connection) or die(mysql_error()); //fetch rows from query $rows = mysql_fetch_assoc($result); // find out how many records there are to update $size = count($_POST['uid']); // start a loop in order to update each record $i = 0; while ($i < $size) { // define each variable $uid = $_POST['uid'][$i]; $fname = $_POST['fname'][$i]; $lname = $_POST['lname'][$i]; $email = $_POST['email'][$i]; // do the update and print out some info just to provide some visual feedback $query = "UPDATE `user` SET `fname` = '$fname', `lname` = '$lname', `email` = '$email' WHERE `uid` = '$uid' "; mysql_query($sql) or die ("Error in query: $query"); print " </tr> <td align='left'><p>$uid</p></td> <td align='left'>$fname</td> <td align='left'>$fname</td> <td align='left'>$lname</td> </tr> "; ++$i; } mysql_close($connection); ?> <tr> <td colspan='4' align='center'> </td> </tr> </table> </td> </tr> </table></div></body></html> Mod edit: [code] . . . [/code] tags added. Hi guys,
I have a problem with my code.
It connects with the database but it doesn't execute anything.
I am trying to update a value in a table but I really don't know what I am doing wrong.
I am trying to change the price based on the meta_value GF-1370
Thank you very much.
Here is Table (Taken from myphpadmin)
meta_id post_id meta_key meta_value
18538
4356
_sku
GF-1370
18541
4356
_price
2.343
and here is my code:
<?php $link = mysql_connect('server', 'username', 'password'); if (!$link) { die('Could not connect: ' . mysql_error()); } echo 'Connected successfully'; mysql_select_db(wordpress_i12dhflgoa); $sql="update `wp_pzvy_postmeta` set `_price` = 5 WHERE `_sku` = 'GF-1370'"; ?> |