PHP - Help With Using Variables To Set Mysql Update
Hi,
I'm only just getting started with php and mysql but I like to go off the deep end. something is wrong with my script. it seems to work up untill it comes to the UPDATE part. It wont actually update the table and the mysql_affected_rows bit returns -1 I've searched for an explanation and can't find one. Can someone tell me what I'm doing wrong Thanks. //connect to mysql $con = mysql_connect("xxx","yyy","zzz"); if (!$con) { die('Could not connect: ' . mysql_error()); } //use the right database mysql_select_db("foo_bar"); //select all cancelled tickets $status_query = "SELECT * FROM jos_vm_orders where order_status = 'X'"; $status_result = mysql_query($status_query) or die(mysql_error()); while ($newArray = mysql_fetch_array($status_result, MYSQL_ASSOC)) { $order_id = $newArray['order_id']; $quantity_query = "SELECT * FROM jos_vm_order_item where order_id = $order_id"; $quantity_result = mysql_query($quantity_query) or die(mysql_error()); while ($newArray2 = mysql_fetch_array($quantity_result, MYSQL_ASSOC)) { $product_quantity = $newArray2[product_quantity]; $order_item_sku = $newArray2[order_item_sku]; echo ("$order_id cancelled $product_quantity tickets sku was $order_item_sku \n"); mysql_query("UPDATE LOW_PRIORITY jos_vm_product SET product_in_stock = product_in_stock + $product_quantity WHERE product_sku = $order_item_sku AND STR_TO_DATE($order_item_sku, '%Y-%d-%m') $quantity_query = "SELECT * FROM jos_vm_order_item where order_id = $order_id"; $quantity_result = mysql_query($quantity_query) or die(mysql_error()); while ($newArray2 = mysql_fetch_array($quantity_result, MYSQL_ASSOC)) { $product_quantity = $newArray2[product_quantity]; $order_item_sku = $newArray2[order_item_sku]; echo ("$order_id cancelled $product_quantity tickets sku was $order_item_sku \n"); mysql_query("UPDATE LOW_PRIORITY jos_vm_product SET product_in_stock = product_in_stock + $product_quantity) WHERE product_sku = $order_item_sku AND STR_TO_DATE($order_item_sku, '%Y-%d-%m') >= CURDATE()"); echo ("$product_quantity tickets released into $order_item_sku \n"); echo ("Affected rows "); echo (mysql_affected_rows()); echo ("\n"); } } mysql_free_result($status_result); mysql_free_result($quantity_result); mysql_close($con); ?> Similar TutorialsCan anyone post a generic update function to update mysql table. The manual approach: update $tablename set $column1='a', $column2='b' where $id=$value; Hi, all... have a basic question here as a newbie that I am... Many times, in some scripts I see (I think, if not mistaken), places where within a echo sentence I see variables echoed like this with no quotes: echo "First Name: $firstName and Last Name: $lastName"; as opposed to like one would expect: echo "First Name: " . $firstName . " and Last Name: " . $lastName"; Sometimes I see that also when variables are used in select/update statements I think.. like this: $query = mysql_query("SELECT FROM table WHERE column = $columnname"); Instead of like this within quotes: $query = mysql_query("SELECT FROM table WHERE column = '$columnname'"); Is it because some of these values may be numbers (numeric) as opposed to "strings"?? Not sure if I make sense... appreciate teh feedback, Thanks! 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> I have lost my record when I run the code below, all fields are empty... Code: [Select] <a href='edit.php?id={$info['person_id']}'><font color='#00AE0A'>Edit User</font> </a> Code: [Select] $sql = "SELECT * FROM person WHERE person_id='{$_REQUEST['id']}' "; $result = mysql_query($sql); if (!$result) { echo("<p>Error performing query: " . mysql_error() . "</p>"); exit(); } if ($row = @mysql_fetch_array($result, MYSQL_ASSOC)) { print " <form action='<?php echo $PHP_SELF;?>' method=\"post\"> <table> <tr> <td><strong>Name</strong></td> <td><input type=\"text\" name=\"fname\" size=\"60\" value=\"$row[fname]\"></td> </tr> <tr> <td><strong>Surname</strong></td> <td><input type=\"text\" name=\"lname\" size=\"60\" value=\"$row[lname]\"></td> </tr> <tr> <td><strong>Email</strong></td> <td><input type=\"text\" name=\"email\" size=\"60\" value=\"$row[email]\"></td> </tr> <tr> <td><strong>Committee</strong></td> <td><input type=\"text\" name=\"committee_no\" size=\"60\" value=\"$row[committee_no]\"></td> </tr> <tr> <td><INPUT type=\"submit\" value=\"Send\"> </td> </tr> </table></form> "; } else { echo("There has been an error" . mysql_error()); } /* closes connection */ ?> <?php $control = mysql_query(" UPDATE person SET fname='{$_REQUEST['fname']}' , lname='{$_REQUEST['lname']}' , email='{$_REQUEST['email']}', committee_no='{$_REQUEST['committee_no']}' WHERE person_id='{$_REQUEST['id']}'"); if($control) { header("Location:".$_SERVER["HTTP_REFERER"].""); } ?> Hey, I have this code, and it's ment to change the name / content of a page that is being put onto a page. Both of the include files are fine as it works for other actions, but this one just returns the error. <?php include "../includes/mysql_connect.php"; include "../includes/info_files.php"; if(isset($_POST['submitted'])) { mysql_query("UPDATE `pages` SET name='$_POST[name]' AND SET content='$_POST[content]' AND SET catt='$_POST[catt]' AND SET page='$_POST[page]' WHERE id='$_POST[id]'") or die('Edit failed'); echo "Page made.<br /><br />"; }else{ $result = mysql_query("SELECT * FROM pages WHERE id='$_GET[page]'"); while($row = mysql_fetch_array($result)) { echo '<form action="" method="post">'; echo '<input type="hidden" name="id" value="' . $row['id'] . '" /><br />'; echo '<strong>Edit: ' . $row['name'] . '</strong><br />'; echo 'Name: <input type="text" name="name" value="' . $row['name'] . '" /><br />'; echo 'Category: <input type="text" name="catt" value="' . $row['catt'] . '" /><br />'; echo 'Page: <input type="text" name="page" value="' . $row['page'] . '" /><br />'; echo '<textarea rows="25" cols="60" name="content">' . $row['content'] . '</textarea><br />'; echo '<input type="submit" name="submitted" value="Edit" />'; echo '</form>'; } } ?> Any help would be great. So there is this code I have here : http://pastebin.com/rwcN7FeJ and I need to find a way to incorporate this code that user Barand gave me Code: [Select] $referName = mysql_real_escape_string($gateway_data['refer']); $query = "UPDATE users a INNER JOIN users b ON a.refer = b.nick SET a.refer = '', b.balance = b.balance + 5 WHERE b.refer = '$referName'"; mysql_query($query); But I havent the damnedest how to do that. If anyone could help me at all, it would be appreciated. I have made this, although i can not seem to the status... changeapp.php Code: [Select] <form method="post" name="memberadd" action="change_app_complete.php"> <label>Name:</label> <select name="member"> <?php $con = mysql_connect("host","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("database",$con); $sqlquery="SELECT * FROM `application` Order By Name"; $result=mysql_query($sqlquery,$con); while($row=mysql_fetch_array($result)) { echo "<option value='".$row['ID']."'>".$row['Name']." (".$row['Status'].")</option>"; } ?> </select> <br> <label>Status:</label> <select name="Status"> <option value="PENDING">PENDING</option> <option value="ACCEPTED">ACCEPTED</option> <option value="DENIED">DENIED</option> <br> <input type="submit" value="submit" /> </form> change_app_complete.php Code: [Select] <?php $status=$_POST['Status']; $con = mysql_connect("host","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("database",$con); $sql="UPDATE application SET Status = '$status' WHERE Name= '$member'"; if(mysql_query($sql,$con)) { echo 'Status Changed.<br /><a href="../applications.php">Return To Members List</a>'; } else { die('Could not submit: ' . mysql_error()); } mysql_close($con); ?> What is wrong? I have the following code that when used seperately work. How would I write an if..else statement that will make them work together? The following code give me an Parse Error, syntax error unexpected T_string. The following if my code I have tried, Code: [Select] if (SELECT tournament FROM weekly_picks WHERE tournament = '$tournament') mysql_query("UPDATE weekly_picks SET player = '$golfer' WHERE tournament = '$tournament' AND user = '$usr'"); else mysql_query("INSERT INTO weekly_picks (t_id, tournament, user, player, backup, timestamp) VALUES ('$t_id', '$tournament', '$usr', '$golfer', '$backup', '$time')",$link) or die('Error, insert query failed'); I also know that values are being stored in the variables. I have this query: Code: [Select] $sql3 = "UPDATE users SET hours = '$newHours', pay = '$newPay', virtualLocation = '$arrival', expDate = '$expDate' WHERE pilotID = '$pilotid'"; I've echoed it out and all the variables put out the correct values. The query works except for the pay section of it. It will update the hours, virtual location, and expiration date but it will not update the pay. It inputs 1.00 when the value echoed in the query is not 1.00. I'm not sure if, because it is a decimal, it changes how the query works. Any help? Thanks. I am trying to update the content of my website which is all stored in a MySQL database. Currently on the page I am displaying all the data stored in the database using MySQL SELECT and a while loop. Using JavaScript when the text is clicked the element changes into a text box allowing the text to be edited. What I want to do is be able to change the data in the text box and then store it into the database updating the current data. Code: [Select] <form method="post" action="editindex.php"> <?php $sql = "SELECT * FROM home ORDER BY id ASC"; $result = mysql_query($sql); while($row = mysql_fetch_assoc($result)){ echo "<span id=\"itm1\" onclick=\"exchange(this);\">" . $row['title'] . "</span><input ondblclick=\"exchange(this);\" id=\"itm1b\" class=\"replace\" type=\"text\ name=\"title\">";?> <input type="submit" value="Save" name="submit"> <input type="hidden" name="id" value="<?php $row['id'] ?>" </form> <?php if (isset ($_POST['submit'])) { $update = "UPDATE home SET title=".$_POST['title']." WHERE id=".$_POST['id'].""; mysql_query($update); } ?> I have more text being output from the while loop below but I just want to get it working on the title first. Any ideas of why the update is not working? Code: [Select] <?php $querySelect = mysql_query("SELECT * FROM `G4V_Videos` WHERE `counter`"); $row = mysql_fetch_assoc($querySelect); $counter = $row['counter']; if (empty($counter)) { $counter = 1; $insert = mysql_query ("INSERT INTO counter VALUES ('counter')"); $printid = (print $data['id']); $printlink = (print $data['link']); } $add = $counter+1; $insertNew = mysql_query("UPDATE G4V_Videos SET counter=('$add') WHERE id = ('$printid') AND link = ('$printlink')") or die (mysql_error()); echo "Video Views"; echo ":"; echo" "; echo"<br />"; echo "$counter"; ?> It shows the same amount of hits on everyvideo instead of just the one video with the id www.game4vids.com this is what i have so far but i cant get it to update the data update page <?php $host="localhost"; // Host name $username="**"; // Mysql username $password="*****"; // Mysql password $db_name="manews"; // Database name $tbl_name="Shows"; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // get value of id that sent from address bar $id=$_GET['id']; // Retrieve data from database $sql="SELECT * FROM $tbl_name WHERE id='$id'"; $result=mysql_query($sql); $rows=mysql_fetch_array($result); ?> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <form name="form1" method="post" action="update_ac.php"> <td> <table width="100%" border="0" cellspacing="1" cellpadding="0"> <tr> <td> </td> <td colspan="3"><strong>Update data in mysql</strong> </td> </tr> <tr> <td align="center"> </td> <td align="center"> </td> <td align="center"> </td> <td align="center"> </td> </tr> <tr> <td align="center"> </td> <td align="center"><strong>Day</strong></td> <td align="center"><strong>Month</strong></td> <td align="center"><strong>Year</strong></td> <td align="center"><strong>Song</strong></td> <td align="center"><strong>Data</strong></td> </tr> <tr> <td> </td> <td align="center"><input name="Day" type="text" id="Day" value="<? echo $rows['Day']; ?>"></td> <td align="center"><input name="Month" type="text" id="Month" value="<? echo $rows['Month']; ?>"></td> <td align="center"><input name="Year" type="text" id="Year" value="<? echo $rows['Year']; ?>" size="15"></td> <td align="center"><input name="Song" type="text" id="Song" value="<? echo $rows['Song']; ?>"></td> <td align="center"><input name="Data" type="text" id="Data" value="<? echo $rows['Data']; ?>" size="15"></td> </tr> <tr> <td> </td> <td><input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>"></td> <td align="center"><input type="submit" name="Submit" value="Submit"></td> <td> </td> </tr> </table> </td> </form> </tr> </table> <? // close connection mysql_close(); ?> update script <?php $host="localhost"; // Host name $username="**"; // Mysql username $password="**"; // Mysql password $db_name="manews"; // Database name $tbl_name="Shows"; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // update data in mysql database $sql="UPDATE $tbl_name SET Day='$Day', Month='$Month', Year='$Year', Year='$Song', Year='$Data' WHERE id='$id'"; $result=mysql_query($sql); // if successfully updated. if($result){ echo "Successful"; echo "<BR>"; echo "<a href='list_records.php'>View result</a>"; } else { echo "ERROR"; } ?> Code: [Select] if(isset($_POST['npassword']) and ($_POST['cpassword'])){ $npassword = $_POST['npassword']; $cpassword = $_POST['cpassword']; $username = $_SESSION['SESS_login']; if($npassword==$cpassword){ $password = md5($npassword); $lol = mysql_query("UPDATE `members` SET `passwd` = '$password' WHERE `login`= '$username';"); echo"Password Changed!"; } } It echos password changed, but its not updating the password. If I run it in phpmyadmin it works fine... So i'm really stuck. Is there something seriously wrong with this code that im missing ? I have written it at least 10-12 different ways and it will NOT update my db.. Code: [Select] <?php mysql_connect('localhost','root',''); mysql_select_db('myDB'); $dates = $_POST['date']; $store = $_POST['store']; // these actually display the correct information mysql_query = ("UPDATE Agency Stores - Table 1 SET date = '".$date."' WHERE F3 = '".$store."' "); ?> there are several other columns in the table. I have tried to put them in as the value they already have and it still didnt work... any ideas ? So i have this following code that doesn't work I am attempting something similar to the following: Code: [Select] mysql_query("UPDATE table SET name='$name' WHERE id=$id"); if (mysql_affected_rows()==0) { mysql_query("INSERT INTO table (id, name) VALUES ('$name',$id); } If the $id row does not exists in the table, mysql_affected_rows() returns 0 and a new $id row gets inserted but if the $id row already exists and UPDATE changes nothing, mysql_affected_rows() still returns 0 and gives an 'duplicate id' error as expected. I know I could use a SELECT to test for the existance of the $id row. In Perl there is an '0E0', 'zero but true', condition to handle this. Is there an equivilant in PHP? Hello there, here is my page I'm having problem with.. Code: [Select] <?php session_start(); require_once 'database.php'; include("header.php"); $username="***"; $password = "****"; $hostname = "localhost"; $database = "***"; $id = $_GET['id']; // Connect to MySQL... $conn = mysql_connect($hostname, $username, $password) or die("Connecting to MySQL failed"); mysql_select_db($database, $conn) or die("Selecting MySQL database failed"); // Run our query, see if session username exists in session field... $sql="select username,gang,gangid from user where username='{$_SESSION['user']}' limit 1"; $result=mysql_query($sql,$conn); // Parse our results into $data (as an associative array)... $data=mysql_fetch_assoc($result); $gangsql="select id,to,gang,gangid from ganginv where id='$id' limit 1"; $gangresult=mysql_query($gangsql,$conn); // Parse our results into $data (as an associative array)... $data2=mysql_fetch_assoc($gangresult); // This is line 24 if ( $data['username'] == $data2['to'] ){ $gang = $data2['gang']; $gangid = $data2['gangid']; $insertelse="UPDATE user SET gang='$gang', gangid='$gangid' WHERE username='{$_SESSION['user']}'"; $insertresultelse=mysql_query($insertelse); }else{ echo "This invite was not for you."; } ?> What this does is it performs to queries to two different tables. Then it matches the usernames ( to make sure it's the same) and then update the table "user" to the column "gang" and "gangid". Here is the error it gives me: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home2/******/ganginv.php on line 24 This invite was not for you. Line 24 is marked. I appreciate all the help/info you have to offer! I'm having problems updating my database, I have 4 fields i want to change. I checked all the { on the page, that's not the problem, I tried to echo information from the database and it displayed my information so that's not the problem, i tried yelling at my computer, that didn't work, i tried to input data into the database with the insert function it worked but is not practical in my situation. I'm probably going to face palm when i find out whats wrong, help please btw, the $_SESSION['usr'] was set in another page and works. Code: [Select] <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Edit Info</title> <link rel="stylesheet" type="text/css" href="demo.css" media="screen" /> </head> <body> <div id="main"> <div class="container"> <font size="5" face="sans-serif">Change Settings <?php echo "{$_SESSION['usr']}"; ?></font> <form action="" method="POST"> <table cellpadding="3" cellspacinf="4" border="0"> <tr> <td>Name</td> <td><input type="text" name="name" /></td> </tr> <tr> <td>Age</td> <td><input type="text" name="age" /></td> </tr> <tr> <td>Gender</td> <td><input type="text" name="mf" /></td> </tr> <tr> <td>Location</td> <td><input type="text" name="loc" /></td> </tr> <tr> <td><input type="submit" name="submit" value="submit" /></td> </tr> </table> </form> <?php if ($_POST['submit']){ define('INCLUDE_CHECK',true); require 'connect.php'; $usr = $_SESSION['usr']; $sql = mysql_query("UPDATE members SET name='{$_POST['name']}', age='{$_POST['age']}, mf='{$_POST['mf']}', loc='{$_POST['loc']}' WHERE usr='{$_SESSION['usr']}'"); if($sql){ echo 'Changes Saved!'; }else{ echo 'Error'; } } ?> </div> </div> </body> </html> Good Day
Please could someone be so gracious as to help me with the following problem.
I am wanting to update a MYSQL database from a Firebird database.
I have tested connecting to both databases individually which works fine, it is just when I put the code together it does not work.
Below is the code
//Firstly I connect to the MYSQL database to see what needs to updated mysql_connect("localhost", "database", "password") or die(mysql_error()); mysql_select_db("database") or die(mysql_error()); $check = "SELECT * FROM table WHERE blah != ''"; $result = mysql_query($check) or die ("Error in query: $check. " . mysql_error()); if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_object($result)) { $blah = $row->blah; // Then I connect to the Firebird database to get the info $dsndb = 'host'; $userdb = 'user'; $passdb = 'password'; try { $dbh = new PDO($dsndb, $userdb, $passdb); $sth = ("SELECT * from table WHERE blah = '$blah'"); foreach ($dbh->query($sth) as $row) { //Then I update the MYSQL database from the Firebird database info $sql = "UPDATE table SET field1 = 'field1', field2 = 'field2', field3 = 'field3' WHERE blah = '$blah'"; $update=mysql_query($sql) or die(mysql_error()); } } } }Your assistance will be greatly appreciated. I have a value that in parts of my code i need to update. Its a number value, stored as TEXT. which i need to add numbers to it, at the moment I am using this to get the current value: Code: [Select] $sql2="SELECT * FROM weekly LIMIT 1"; $result2=mysql_query($sql2); $row2 = mysql_fetch_array( $result2 ); $rollingjackpot = $row2['rollingjackpot']; then i am adding the value to the varible, then using UPDATE to update it again, cant this be done in a simple query? something like: Code: [Select] $query = mysql_query("UPDATE weekly SET `rollingjackpot` + $amount WHERE `id` = '1'") or die(mysql_error()); |