PHP - Having Trouble Updating A Variable To Database + Paypal Integration
Hello Everyone,
I am pretty new to the forums and was curious if i could get some help here. Basically, in a nutshell, i have PayPal integrated into my website. I will use this to collect money from clients. when a client logs into his/her account they see their balance (which is pulled from the database to correspond with the user that's logged-in). Now, everytime a payment is submitted a notify_url is contacted after payment has been verified, that notify_url is the code written below. What I am trying to execute here is when this notify_url is called the current balance is reduced from the amount paid through paypal. In the second If condition, you will see that the word success is being entered into the paypal.txt file, which is working perfectly fine. Now, you will also see the variable $update_balance; which is suppose to update the original balance with the balance paid through PayPal BUT IT'S NOT!! WHY?? LOL Thank You in advance! <?php ob_start(); session_start(); include_once ('/home/rdewebde/public_html/includes/paypal.php'); $myPaypal = new Paypal(); $myPaypal->ipnLog = TRUE; include_once "/home/rdewebde/public_html/includes/_config.php"; $username = "".$_SESSION['username'].""; $users_data = mysql_query("SELECT * FROM `members` WHERE `username`='".$username."'"); $user_info = mysql_fetch_array($users_data); $current_amount = $user_info['balance']; $deduct_amount = $myPaypal->ipnData['payment_gross']; $new_amount = $current_amount - $deduct_amount; $update_balance = mysql_query("UPDATE `members` SET `balance` = '$new_amount' WHERE `username` = '".$username."'"); if ($myPaypal->validateIpn()) { if ($myPaypal->ipnData['payment_status'] == 'Completed') { $update_balance; file_put_contents('/home/rdewebde/public_html/lounge/paypal.txt', 'SUCCESS'); } else { file_put_contents('/home/rdewebde/public_html/lounge/paypal.txt', "FAILURE\n\n" . $myPaypal->ipnData); } } ?> Similar TutorialsHey guys, I have made an admin page for a game Im working on to quickly allow me to update many aspects of the game. My form is sending the correct data because i can echo the $_post but for some reason it isnt updating my database. I just get a blank white page. Could anyone see what i have done wrong. Thanks Code: [Select] <?php require($DOCUMENT_ROOT . "/game/includes/connection.php"); require($DOCUMENT_ROOT . "/game/includes/settings.php"); ?> <?php $name = $_POST['admin_name']; $img = $_POST['admin_img']; $current_hp = $_POST['admin_current_hp']; $max_hp = $_POST['admin_max_hp']; $current_energy = $_POST['admin_current_energy']; $max_energy = $_POST['admin_max_energy']; $level = $_POST['admin_level']; $exp_total = $_POST['admin_exp_total']; $exp = $_POST['admin_exp']; $exp_level = $_POST['admin_exp_level']; $pos_x = $_POST['admin_pos_x']; $pos_y = $_POST['admin_pos_y']; $potion = $_POST['admin_potion']; $ether = $_POST['admin_ether']; $elixir = $_POST['admin_elixir']; $zenni = $_POST['admin_zenni']; $sector = $_POST['admin_sector']; $battle = $_POST['admin_battle']; ?> <?php $sql_1 = "UPDATE game_character SET name='$name', img='$img', current_hp='$current_hp', max_hp='$max_hp', current energy='$current_energy', max_energy='$max_energy', level='$level', exp_total='$exp_total', exp='$exp', exp_level='$exp_level', pos_x='$pos_x', pos_y='$pos_y', potion='$potion', ether='$ether', elixir='$elixir', zenni='$zenni' WHERE id=1"; $sql_2 = "UPDATE game_status SET sector='$sector', battle='$battle' WHERE id=1"; $statement_1 = $dbh->prepare($sql_1); $statement_2 = $dbh->prepare($sql_2); $statement_1->execute(); $statement_2->execute(); ?> <SCRIPT LANGUAGE="JavaScript"> redirTime = "1"; redirURL = "<?php echo $r_admin ?>"; function redirTimer() { self.setTimeout("self.location.href = redirURL;",redirTime); } </script> <BODY onLoad="redirTimer()"> hi, I'm trying to integrate paypal integration. it is integrated successfully and I've checked on my test account too. i want that as user purchase package he should able to download the file. to do that i want to set return variable. as user complete the payment process on paypal , it should auto come back to my website. as he'll be back I'll set his flag to paid and allow him to download file. the problem I'm facing is on my test account. when i paid money. i didn't return to my website. so i don't know to set his flag to true. any one know its best solution??? i want immediate response to client to pay online. Please advise... Thanks Hi Everybody I am doing online education portal. Teachers and students will be registered on this site. Student will search teachers and create schedule to learn subjects. For that student can pay to the teacher some amount. So that student can increase his/her balance. That means he can transfer some money to website company account through credit card or paypal or google checkout. I did credit card part. But i am not getting any idea to do in paypal. That means student can enter amount and click paypal button, it should show paypal page. So that he can login into his paypal account and pay that amount. After pay that amount we can get IPN (Instant Payment Notification). So that we can store that amount into my database under that student ID. Please tell me how can i do this? Hi, I just integrate my website with paypal test account. It works fine. now i want that if i pay on paypal website it should return to my website. i use following code to do that <input type="hidden" name="return" value="http://www.miricreation.ae.com/shopping-cart-details.php"> but it didn't working. i also enable auto return url into my test account. but no luck. is there anything need to do for this in code?????????? Please help Thanks Hi, I'm integrated paypal standard integration on my website. It integrated successfully.. we collect the data on website and send all info to paypal. in database order table. I set the status to 0 which means order is pending. Now i'm confused how it'll be 1? when i'll come to know that client has paid the payment. do i need to set it flag manual in admin panel after check into my paypal account? or do i need to send some parameter on return valraible. if he i'll return to that page then query to set flag 1. Please help me on this. and let me know which one is best method??? Looking forward. Best regards Hi, I am integrating Paypal Pro into my checkout and struggling to get it to work correctly.
I am using this code to connect to paypal - which all works correctly, processes payments as it should and send paypal receipts to the customer and to me.
The problem is that when Paypal redirects back to my receipt page, it is not triggering the email (customer_mail_new.php and client_mail_new.php) to tell me what exactly they customer has ordered!
I've been staring at this code for hours now and wonder if anyone can see anything obvious that I have (or haven't) done that is causing the emails to not send at the end of the receipt page?
(paypal.php)
<?php hey guys. i am not too familiar with how loop works.. or in my case particularly. Here is the situation. i am trying to pass multiple transactions in a single click using paypal's doDirectPayment nvp api. The credit card number, name, address will be the same but the "invoice number" and "amount" will be different for each transaction. The way i have it now is that if there are multiple transactions, it processes them as a whole so if there are four $25 transactions, it charges one amount, $100 and provides one transaction id. I'd like to be able to set those transactions in a loop, so each transaction is billed individually and have its own transaction id returned from Paypal. an example would be this: item_ID-----amount 1 ----- $25 2 ----- $25 3 ----- $25 4 ----- $25 total ------ $100 the code i have currently is this: Code: [Select] <?php /** DoDirectPayment NVP example; last modified 08MAY23. * * Process a credit card payment. */ $environment = 'sandbox'; // or 'beta-sandbox' or 'live' /** * Send HTTP POST Request * * @param string The API method name * @param string The POST Message fields in &name=value pair format * @return array Parsed HTTP Response body */ //function PPHttpPost($methodName_, $nvpStr_) {} $userRes=mysql_query("SELECT * FROM user where id='".$_SESSION['SESS_USERID']."'"); $userRow=mysql_fetch_array($userRes); // Set request-specific fields. $fullname=explode(" ",$userRow['fullname']); $paymentType = urlencode('Sale'); // or 'Authorization' $firstName = urlencode($fullname[0]); $lastName = urlencode($fullname[1]); $creditCardType = urlencode($card_type); $creditCardNumber = urlencode($card_no); // Month must be padded with leading zero $padDateMonth = urlencode(str_pad($exp_month, 2, '0', STR_PAD_LEFT)); $expYr="20".substr($exp_year,-2); $expDateYear = urlencode($expYr); $cvv2Number = urlencode($cvv2); $address1 = urlencode($userRow['address1']); $address2 = urlencode($userRow['address2']); $city = urlencode($userRow['city']); $state = urlencode($userRow['state']); $zip = urlencode($userRow['zip']); $country = urlencode('US'); // US or other valid country code $amount = urlencode($totalamt); $currencyID = urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD') // Add request-specific fields to the request string. $nvpStr = "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber". "&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName". "&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID"; // Execute the API operation; see the PPHttpPost function above. $httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr); if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) { if($s_list!="") { $updRes=mysql_query("UPDATE cars set s_fee_paid_status='1',seller_paid_date=now() where id in (".$s_list.")"); } if($b_list!="") { $updRes=mysql_query("UPDATE cars set b_fee_paid_status='1',buyer_paid_date=now() where id in (".$b_list.")"); } $exp_date=$exp_month."/".$exp_year; $updRes=mysql_query("UPDATE user set nameoncard='".$nameoncard."',card_type='".$card_type."',card_no='".$card_no."',cvv2='".$cvv2."',exp_date='".$exp_date."' where id='".$_SESSION['SESS_USERID']."'"); //$msgs=urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]); echo "<script> window.location='somewebfile.php?msgs=1'; </script>"; exit; } else { $msgs=urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]); /*echo "<script> window.location='somewebfile.php?msgs=2'; </script>"; exit;*/ } ?> I have a site with a shopping cart that uses a paypal buy now button. The button seems to work fine, when I click it everything in my cart on my site shows up how its suppose to in the paypal checkout page. Then problem is when I try to log into my buyer sandbox account. It's telling me its the wrong email or password when I know for a fact it is correct. I know I need to be logged in to the sandbox developer account while using it, but it still wont let me log in. My site tried to do multiple items using the value _cart for the cmd hidden paypal input and upload. However when I use another example that only does one item at a time and has preset variables my sandbox paypal accoung logs in fine. This makes me think there is something wrong with my code. Here is the code to build my paypal button for my site Code: [Select] $cartOutput = ""; $cartTotal = ""; $pp_checkout_btn = ''; $product_id_array = ''; if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>"; } else { // Start PayPal Checkout Button $pp_checkout_btn .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" accept-charset="utf-8"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="upload" value="1"> <input type="hidden" name="business" value="pwang@sofpower.com">'; // Start the For Each loop $i = 0; foreach ($_SESSION["cart_array"] as $each_item) { $item_id = $each_item['item_id']; $query = "SELECT * FROM product WHERE id='$item_id' LIMIT 1"; $result = $db_obj->query($query); if($db_obj->error) exit ($db_obj->error); //$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1"); while ($row = $result->fetch_array(MYSQLI_ASSOC)) { $product_name = $row["product_name"]; $price = $row["price"]; $details = $row["details"]; } $pricetotal = $price * $each_item['quantity']; $cartTotal = $pricetotal + $cartTotal; $_SESSION["cart"] = $cartTotal; setlocale(LC_MONETARY, "en_US"); //$pricetotal = money_format("%10.2n", $pricetotal); // Dynamic Checkout Btn Assembly $x = $i + 1; $pp_checkout_btn .= '<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '"> <input type="hidden" name="amount_'. $x . '" value="' . $price . '"> <input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '"> '; // Create the product array variable $product_id_array .= "$item_id-".$each_item['quantity'].","; // Dynamic table row assembly $cartOutput .= "<tr>"; $cartOutput .= '<td><a href="product.php?id=' . $item_id . '">' . $product_name . '</a><br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name. '" width="40" height="52" border="1" /></td>'; $cartOutput .= '<td>' . $details . '</td>'; $cartOutput .= '<td>$' . $price . '</td>'; $cartOutput .= '<td><form action="cart.php" method="post"> <input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" /> <input name="adjustBtn' . $item_id . '" type="submit" value="change" /> <input name="item_to_adjust" type="hidden" value="' . $item_id . '" /> </form></td>'; //$cartOutput .= '<td>' . $each_item['quantity'] . '</td>'; $cartOutput .= '<td>' . $pricetotal . '</td>'; $cartOutput .= '<td><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>'; $cartOutput .= '</tr>'; $i++; } setlocale(LC_MONETARY, "en_US"); //$cartTotal = money_format("%10.2n", $cartTotal); $cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : ".$cartTotal." USD</div>"; // Finish the Paypal Checkout Btn $pp_checkout_btn .= ' <input type="hidden" name="return" value="http://webdev.cs.kent.edu/~jfunchio/wp2/HW2/checkout_complete.php"> <input type="hidden" name="cancel_return" value="http://webdev.cs.kent.edu/~jfunchio/wp2/HW2/paypal_cancel.php"> <input type="image" src="https://www.paypal.com/images/x-click-butcc.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!"> </form>'; } Here is the example that works Code: [Select] <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta charset="utf-8"/> <title>SuperStore.Com</title></head> <body style="margin: 50px"> <h2>Purchase Our Product Online</h2> <p><img src="hammer.jpeg" alt="Hammer" style="vertical-align: middle" /> Hammer for $4.49.</p> <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" accept-charset="utf-8"> <input type="hidden" name="cmd" value="_xclick" /> <input type="hidden" name="business" value="jfunchio@kent.edu" /> <input type="hidden" name="item_name" value="Hammer" /> <input type="hidden" name="amount" value="4.49" /> <input id="tt" type="hidden" name="return" value="success return URL" /> <input id="ff" type="hidden" name="cancel_return" value="failure return URL" /> <!-- company logo for PayPal page --> <input type="hidden" name="image_url" value="http://www.sofpower.com/images/sofppal.gif" /> <input type="hidden" name="cn" value="Special Instructions (optional)" /> <table style="background-color: #ddffee"> <tr><td> </td></tr> <tr><td>Customer Full Name</td><td> <input type="text" name="cnm" size="30" maxlength="50" /></td></tr> <tr><td><input type="hidden" name="on0" value="customer email address" /> Customer email</td> <td><input type="text" name="os0" size="30" maxlength="100" /></td></tr> <tr><td><input type="hidden" name="on1" value="customer institution" /> Customer institution</td> <td><input type="text" name="os1" size="30" maxlength="100" /></td></tr> <tr><td> </td></tr> </table><br /> <input type="image" src="https://www.paypal.com/images/x-click-butcc.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!" /> </form> <p>When payment has been received, we will also send a confirmation to you by email.<br /> After ordering, if you need to get in touch with us, please send email to<br /> <tt>customer-service@superstore.com</tt>.</p> <pre> </pre> </body></html> I have set up u chat page on my site and would like to know how to make it use the logged in members user name from my database rather than assigning them a guest name, i think i have found the code that needs editing but i have no idea what needs to be done. I think the editing needs to be done in this code somewhere but i could be wrong, Please help. Code: [Select] <?php require_once dirname(__FILE__)."/src/phpfreechat.class.php"; $params = array(); $params["title"] = "Quick chat"; $params["nick"] = "guest".rand(1,1000); // setup the intitial nickname $params['firstisadmin'] = true; //$params["isadmin"] = true; // makes everybody admin: do not use it on production servers ;) $params["serverid"] = md5(__FILE__); // calculate a unique id for this chat $params["debug"] = false; $chat = new phpFreeChat( $params ); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>phpFreeChat- Sources Index</title> <link rel="stylesheet" title="classic" type="text/css" href="style/generic.css" /> <link rel="stylesheet" title="classic" type="text/css" href="style/header.css" /> <link rel="stylesheet" title="classic" type="text/css" href="style/footer.css" /> <link rel="stylesheet" title="classic" type="text/css" href="style/menu.css" /> <link rel="stylesheet" title="classic" type="text/css" href="style/content.css" /> </head> <body> <div class="header"> <img alt="phpFreeChat" src="style/logo.gif" class="logo2" /> </div> <div class="menu"> <ul> <li class="sub title">General</li> <li> <ul class="sub"> <li class="item"> <a href="demo/">Demos</a> </li> <?php if (file_exists(dirname(__FILE__)."/checkmd5.php")) { ?> <li> <a href="checkmd5.php">Check md5</a> </li> <?php } ?> <!-- <li class="item"> <a href="admin/">Administration</a> </li> --> </ul> </li> <li class="sub title">Documentation</li> <li> <ul> <li class="item"> <a href="http://www.phpfreechat.net/overview">Overview</a> </li> <li class="item"> <a href="http://www.phpfreechat.net/quickstart">Quickstart</a> </li> <li class="item"> <a href="http://www.phpfreechat.net/parameters">Parameters list</a> </li> <li class="item"> <a href="http://www.phpfreechat.net/faq">FAQ</a> </li> <li class="item"> <a href="http://www.phpfreechat.net/advanced-configuration">Advanced configuration</a> </li> <li class="item"> <a href="http://www.phpfreechat.net/customize">Customize</a> </li> </ul> </li> </ul> <p class="partner"> <a href="http://www.phpfreechat.net"><img alt="phpfreechat.net" src="style/logo_88x31.gif" /></a><br/> </p> </div> <div class="content"> <?php $chat->printChat(); ?> <?php if (isset($params["isadmin"]) && $params["isadmin"]) { ?> <p style="color:red;font-weight:bold;">Warning: because of "isadmin" parameter, everybody is admin. Please modify this script before using it on production servers !</p> <?php } ?> </div> <div class="footer"> <span class="partners">phpFreeChat partners:</span> <a href="http://www.jeu-gratuit.net">jeux gratuits</a> | <a href="http://jeux-flash.jeu-gratuit.net">jeux flash</a> | <a href="http://www.pronofun.com">pronofun</a> | <a href="http://areno.jeu-gratuit.net">areno</a> | <a href="http://www.micropolia.com">micropolia</a> | <a href="http://www.zeitoun.net">zeitoun</a> | <a href="http://federation.jeu-gratuit.net">federation</a> </div> </body></html> Well this is the code I currently have, it is derived from ajax organic tabs codes. Code: [Select] <? if($filename == "profile"){ ?> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script> <script src="js/tabs.js"></script> <script> $(function() { $("#profile").organicTabs(); }); </script> <? } ?> It may look fine this way, but rather inflexible if I wish to implement more tabs in future instead of just for the profile page. Assuming I have profile.php, members.php and stats.php and all of the three script files use tab system, the codes will become: Code: [Select] <? if($filename == "profile"){ ?> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script> <script src="js/tabs.js"></script> <script> $(function() { $("#profile").organicTabs(); }); </script> <? } elseif($filename == "members"){ ?> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script> <script src="js/tabs.js"></script> <script> $(function() { $("#members").organicTabs(); }); </script> <? } elseif($filename == "stats"){ ?> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script> <script src="js/tabs.js"></script> <script> $(function() { $("#stats").organicTabs(); }); </script> <? } ?> Which can get even more tedious as more and more pages needs to adopt tabs system. I wonder if there is a way to simplify the code by passing the php variable $filename directly into javascript tabs definition in this line, where the part $("#profile") changes as filename changes? Please help... Code: [Select] $("#profile").organicTabs(); Hello, I am developing a PayPal IPN interface which works fine, all is passed for verification and comes back 'VALID'. After validation with PayPal I update a users subscription and do the rest I want to do, but there is one thing really really irritating me. It seems to be that this one particular table in the database does not want to accept anything I throw at it through PHP. Here's the code: Code: [Select] $query = "INSERT INTO `ipn_txn_logs` ( `date` , `payment_reason` , `pp_txn_id` , `pp_amount` , `pp_txn_charge` , `pp_txn_net_amount` , `ltj_txn_id` , `description` , `failsafe` , `member` ) VALUES ( '$date', 'subscribe', '$txn[txn_id]', '$txn[payment_amount]', '$txn[payment_charges]', '$txn[net_payment]', '$txn[custom]', '$desc', 'yes', '$fname $lname')"; $query = mysql_query($query); The array is set on the IPN return using all values from PayPal. The database will insert when all variable and arrays are left out of the INSERT and replaced with just the number 1.. I am unable to see a PHP error as it's done in the background after a PayPal response... is there anyway to collect this error? Also, any suggestions on this fault? George.[/code] i have this small problem trying to update the database.... what i have is a members site in which they can view a variety of topics, however i want the user to be able to say delete a topic they are not interested in but still keep that topic open to other users who have not blocked it I'm tying to figure out how to do this, i initially had the following code: $update_db = mysql_query("UPDATE topics SET view='2' WHERE topicID='$topicID'") or die(mysql_error()); I had it set to to 2 meaning that all the topics that were set to 1 were visible to the user, only those they blocked were set to 2 and only be blocked to those users who blocked them not everyone The problem with that was that it blocked it to everyone Can anyone help me? ok it updates the posts table , but not the notifications table , helP! Code: [Select] <?php include("../includes.php"); $session =$logOptions_id; if($session) { $id = $_POST['id']; if(!$id) { $id = $session; } $post = mysql_real_escape_string($_POST['post']); $date = mktime(); $action_type = 0; mysql_query("INSERT INTO posts SET to_id='$id',from_id='$session',post='$post',type='$action_type',date='$date'"); $post_id = mysql_insert_id(); $query = mysql_query("SELECT id,to_id,from_id,post,type,state,date FROM posts WHERE id='$post_id' AND state='0' ORDER BY id DESC LIMIT 15"); print posts($query, "newPost"); if($id!=$session) { mysql_query("INSERT INTO notifications SET user_id='$id', from_id='$session', post_id='$post_id', action_type='$action_type', date='$date'"); } } ?> Hey all, I've recently been coding a Bank for my game in which users can desposit there money into. But while coding it I've came though a few errors in which I carn't seem to sort <?php session_start(); include_once ("includes/functions.php"); include ("includes/config.php"); require ("crewtop.php"); logincheck(); ini_set ('display_errors', 1); error_reporting (E_ALL); $username = $_SESSION['username']; $getuser = mysql_query("SELECT * FROM users WHERE username='$username'"); $user = mysql_fetch_object($getuser); $themembers = mysql_query("SELECT * FROM users WHERE crew = '$user->crew'"); $ammoutmembers = mysql_num_rows($themembers); $crew = mysql_query("SELECT * FROM crews WHERE name = '$user->crew'"); $crewstuff = mysql_fetch_object($crew); // Got everything needed.... if ($_POST['desposit']){ $desposit = strip_tags($_POST['desposit']); if ($desposit > $user->money){ // *** This Line *** echo ("You haven't got that much Money to Desposit!"); }elseif ($desposit <= $user->money){ if (ereg('[^0-9]',$desposit)){ echo ("Invalid Numbers Posted!"); }elseif(!ereg('[^0-9]',$desposit)){ mysql_query("UPDATE crews SET bank=bank+$desposit WHERE name='$user->crew'"); mysql_query("UPDATE users SET money=money-$desposit WHERE username='$username'"); echo ('You successfully Deposited £".number_format($desposit)."!'); } } } /* Deposit done - Now Withdraw... */ if ($_POST['withdraw']){ $withdraw = strip_tags($_POST['withdraw']); if ($withdraw > $crewstuff->bank){ // *** This Line *** echo ("You don't have that much Money in the Bank!"); }elseif ($withdraw <= $crewstuff->bank){ if (ereg('[^0-9]',$withdraw)){ echo "Invalid Numbers Posted!"; }elseif(!ereg('[^0-9]',$withdraw)){ $leftinbank = $crewstuff->bank - $withdraw; mysql_query("UPDATE crews SET bank=bank-$withdraw WHERE name='$user->crew'"); mysql_query("UPDATE users SET money=money+$withdraw WHERE username='$username'"); echo ('£".number_format($withdraw)." has been Withdraw from the Crew Bank!'); } } } // Withdraw done! ?> <html> <head> <title>Crew Bank || SD</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body class='body'> <form action='' method='POST' name='crewbank'> <?php echo ("$username , $user->money"); ?> <?php if ($username != $crewstuff->boss || $username != $crewstuff->coowner || $username != $crewstuff->underboss || $username == $crewstuff->recruiter || $username == $crewstuff->recruiterone || $crewstuff->boss == $username || $crewstuff->coowner == $username || $crewstuff->underboss == $username){ ?> <table width='50%' cellpadding='0' cellspacing='0' border='1' class='table' colspan='2' align='center'> <tr> <td class='header' align='center' colspan='2'>Crew Bank</td> </tr> <tr> <td class='omg' colspan='2' align='center'>You Have <strong>£<?php echo "".number_format($crewstuff->bank).""; ?></strong> in the Crew Bank!</td> </tr> <tr> <td align='center' width='50%'>Deposit:</td><td align='center' width='50%'><input type='text' name='desposit' class='input' id='desposit'></td> </tr> <tr> <td align='center' colspan='2' align='center'><input type='submit' name='desposit' class='button' id='despositmoney' Value='Deposit!'></td> </tr> <?php } // Boss ?> </table> <br /> <?php if ($crewstuff->boss == $username || $crewstuff->coowner == $username || $crewstuff->underboss == $username){ ?> <table width='50%' cellpadding='0' cellspacing='0' border='1' class='table' colspan='2' align='center'> <tr> <td class='header' align='center' colspan='2'>Crew Bank - Withdraw</td> </tr> <tr> <td class='omg' align='center' colspan='2'>You carn't Withdraw more Money then there is in your Bank!</td> </tr> </tr> <tr> <td align='center' width='50%'>Withdraw:</td><td width='50%' align='center'><input type='text' name='withdraw' class='input' id='withdraw'></td> </tr> <tr> <td align='center' colspan='2' align='center'><input type='submit' name='withdraw' class='button' id='withdrawmoney' Value='Withdraw!'></td> </tr> </table> <?php } // Boss .. Underboss ?> </form> </body> </html> The two lines with the Comments on " // *** This Line *** " are the parts I've got a problem with. When a User is either despositing or Withdrawing there money it says there isn't enouth Money in the Bank, or that they don't have enouth Money, even when they have enouth. Anyone see why its saying the Error? Thanks in advance why does this code not update database.....any errors you see off the bat? none of the messages are displaying for whether it posts or not......so I think there is something wrong with posting or a loop or something. Code: [Select] <?php session_start(); include "config2.php"; if (!isset($_SESSION['id'])) { echo 'Please <a href="login.php">log in</a> to access your account'; exit(); } //Connect to the database through our include include_once "connect_to_mysql.php"; // Place Session variable 'id' into local variable $userid = $_SESSION['id']; ?> <?php //action: view users ----------------------------------------------------------------------------- if (isset($_GET['viewUsers'])) { //get all active users $query = "SELECT name, username, phone, address, city, state, zip, cell, email, accounttype, badges, password, rank, userid FROM members WHERE userid=userid"; $rs = mysql_query($query); ?> <table width="563" border='1'> <tr> <th width="54">Name</th><th width="84">Username</th><th width="47">Email</th> <th width="148">Access Level</th> <th width="105"> </th> <th width="85"> </th> </tr> <?php //show the users while ($row = mysql_fetch_assoc($rs)) { ?> <tr> <td><?php echo $row['name'];?></td> <td><?php echo $row['username'];?></td> <td><?php echo $row['email'];?></td> <td><?php echo $row['accounttype']?></td> <td> </td> <td><a href='admin.php?edit&id=<?php echo $row['userid'];?>'>Edit</a>, <a href='admin.php?delete&id=<?php echo $row['userid'];?>'>Delete</a></td> </tr> <?php } ?> </table> <?php } //action: edit user ----------------------------------------------------------------------------- if (isset($_GET['edit']) && isset($_GET['id'])) { $userid = (int) $_GET['id']; if ($userid == 0) { die("Invalid ID provided."); } //execution when completed the edit user form and pressed submit button --------------------- if (isset($_POST['editUser'])) { //validate data ------------------------------------------------------------------------ //check empty fields $notRequired = array("email","phone","address", "city", "state","zip","cell" ); //passwords won't be checked, as they are not required foreach ($_POST as $k=>$v) { if ($v == "" && !in_array($k,$notRequired)) { $error[$k] = "<strong>This field is empty</strong>"; } } //escape string $name = "mysql_real_escape_string{$_POST['fname']} {$_POST['last']}"; $phone = mysql_real_escape_string($_POST['phone']); $address = mysql_real_escape_string($_POST['address']); $city = mysql_real_escape_string($_POST['city']); $state = mysql_real_escape_string($_POST['state']); $zip = mysql_real_escape_string($_POST['zip']); $email = mysql_real_escape_string($_POST['email']); $cell = mysql_real_escape_string($_POST['cell']); $username = mysql_real_escape_string($_POST['username']); $last = mysql_real_escape_string($_POST['last']); $first = mysql_real_escape_string($_POST['fname']); //check email validation, the function is available at config.php //check username exists in database $res = mysql_query("SELECT username FROM members WHERE username='".$username."' AND username != '".$username."'"); if (mysql_num_rows($res) == 1) { $error['username'] .= " <strong>Username already existst in database!</strong>"; } //check both passwords are the same when password fields are not empty //end validate data --------------------------------------------------------------------- //save to database when no errors are detected ------------------------------------------ if (count($error) == 0) { $query = "UPDATE members SET username='$username', email='$email', name='".$name."', phone='".$phone."',address='".$address."', city='".$city."',state='".$state."', zip='".$zip."',cell='".$cell."',badges='".$badges."', rank='".$rank."', first='".$first."', last='".$last."' WHERE userid='".$_GET['userid']."'"; $query1 = "UPDATE sessions SET username='".$username."', email='".$email."',name='".$name."', phone='".$phone."',address='".$address."', city='".$city."',state='".$state."', zip='".$zip."',cell='".$cell."',badges='".$badges."', rank='".$rank."' WHERE id='".$userid."'"; //update username session if you edit yourself if ($userid == $_SESSION['auth_admin_userid']) { $_SESSION['auth_admin_username'] = $username; } if (mysql_query($query)|| mysql_query($query1)) { echo "<p><strong>User has been edited and saved to the database.</strong></p>"; } else { echo "<strong>User has NOT been edited and saved into the database. ".mysql_error()."</strong>"; } } } //get user from the database and put data into $_POST variables. $rs = mysql_query("SELECT first, last, username, phone, address, city, state, zip, cell, email, badges, rank, accounttype FROM members WHERE userid = ".$userid.""); if (mysql_num_rows($rs) == 0) { die("User does not exists!"); } $row = mysql_fetch_assoc($rs); $_POST['fname'] = $row['first']; $_POST['last'] = $row['last']; $_POST['username'] = $row['username']; $_POST['phone'] = $row['phone']; $_POST['address'] = $row['address']; $_POST['city'] = $row['city']; $_POST['state'] = $row['state']; $_POST['zip'] = $row['zip']; $_POST['cell'] = $row['cell']; $_POST['email'] = $row['email']; $_POST['badges'] = $row['badges']; $_POST['rank'] = $row['rank']; $_POST['accounttype'] = $row['accounttype']; //if is admin, then $_POST['admin'] exists ?> <form action="admin.php?edit&id=<?php echo $userid; ?>" method="post"> <div id="TabbedPanels1" class="TabbedPanels"> <ul class="TabbedPanelsTabGroup"> <li class="TabbedPanelsTab" tabindex="0">My Info</li> <li class="TabbedPanelsTab" tabindex="0">Merit Badges</li> <li class="TabbedPanelsTab" tabindex="0">Scout Rank</li> </ul> <div class="TabbedPanelsContentGroup"> <div class="TabbedPanelsContent"> <table align="center" cellpadding="8" cellspacing="8"> <tr> <td><div align="right">First Name:</div></td> <td> <input type="text" name="name" value='<?php echo $_POST['fname'];?>' /> <?php echo(isset($error['fname']))?$error['fname']:"";?></td> </tr> <tr> <td><div align="right">Last Name:</div></td> <td> <input type="text" name="name" value='<?php echo $_POST['last'];?>' /> <?php echo(isset($error['last']))?$error['last']:"";?></td> </tr> <tr> <td><div>Phone Number:</div></td> <td><input type="text" name="phone" value='<?php echo $_POST['phone'];?>' /> <?php echo(isset($error['phone']))?$error['phone']:"";?></td> </tr> <tr> <td><div align="right">Address:</div></td> <td><input type="text" name="address" value='<?php echo $_POST['address'];?>' /> <?php echo(isset($error['address']))?$error['address']:"";?></td> </tr> <tr> <td><div align="right">City:</div></td> <td><input type="text" name="city" value='<?php echo $_POST['city'];?>' /> <?php echo(isset($error['city']))?$error['city']:"";?></td> </tr> <tr> <td><div align="right">State:</div></td> <td><input type="text" name="state" value='<?php echo $_POST['state'];?>' /> <?php echo(isset($error['state']))?$error['state']:"";?></td> </tr> <tr> <td><div align="right">Zip Code:</div></td> <td><input type="text" name="zip" value='<?php echo $_POST['zip'];?>' /> <?php echo(isset($error['zip']))?$error['zip']:"";?></td> </tr> <tr> <td><div align="right">Email:</div></td> <td> <input type="text" name="email" value='<?php echo $_POST['email'];?>' /> <?php echo(isset($error['email']))?$error['email']:"";?></td> </tr> <tr> <td><div align="right">Cell Phone:</div></td> <td><input type="text" name="cell" value='<?php echo $_POST['cell'];?>' /> <?php echo(isset($error['cell']))?$error['cell']:"";?></td> </tr> <tr> <td class="aaaaaaa" align="right"><div>Username:</div></td> <td><label for="username"></label> <input type="text" name="username" value='<?php echo $_POST['username'];?>' /> <?php echo(isset($error['username']))?$error['username']:"";?> </td> </tr> <input name="userid" type="hidden" value="<?php echo $userid; ?>" /> </table> <p> </div> <div class="TabbedPanelsContent"> <label for="badges"></label> <input name="badges" type="text" id="badges" value='<?php echo $_POST['badges'];?>' /> <?php echo(isset($error['badges']))?$error['badges']:"";?> </div> <div class="TabbedPanelsContent"> <input name="rank" type="text" id="rank" value='<?php echo $_POST['rank'];?>' /> <?php echo(isset($error['rank']))?$error['rank']:"";?> </div> </div> </div> <input name="editUser" type="submit" value="Save" /> </form> <p> <script type="text/javascript"> var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1"); </script> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <?php } ?> <br /><br /> </div></div> <script type="text/javascript"> var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"../SpryAssets/SpryMenuBarDownHover.gif", imgRight:"../SpryAssets/SpryMenuBarRightHover.gif"}); </script> so my database table already exists but i need to add new columns to the table so this is how the table looks now
CREATE TABLE IF NOT EXISTS `users` ( `id` int(255) NOT NULL AUTO_INCREMENT, `birthday` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1-1-1990', `comment_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `confirm_followers` int(11) NOT NULL DEFAULT '0', `current_city` text COLLATE utf8_unicode_ci NOT NULL, `follow_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `gender` varchar(6) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'male', `hometown` text COLLATE utf8_unicode_ci NOT NULL, `message_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `post_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `timeline_post_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;and this is what I need it to look.... but every time I insert in the sql to do the update but it does not do it as the table already there... CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT NOT NULL, `job_title` mediumtext COLLATE utf8_unicode_ci NOT NULL, `job_at` mediumtext COLLATE utf8_unicode_ci NOT NULL, `birthday` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '1-1-1990', `comment_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `confirm_followers` int(11) NOT NULL DEFAULT '0', `current_city` text COLLATE utf8_unicode_ci NOT NULL, `relationship` varchar(15) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Not Applicable', `relationship_to` mediumtext COLLATE utf8_unicode_ci NOT NULL, `follow_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `gender` varchar(6) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'male', `hometown` text COLLATE utf8_unicode_ci NOT NULL, `message_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `post_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', `timeline_post_privacy` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'everyone', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;how can I do this update>? its ok i know how to do this.. but the code i sell needs this update but i cant get them to delete there table as there mybe data already in the table Hello, I have been staring at my screen for the last couple of days and have finally run out of solutions. I have the code below where the data is generated form another page. The correct data is displayed but for some reason when I try to alter any data it does not work. I simply get the message, "Your profile has been successfully updated..." but nothing has been changed in the database. I think the code is not connecting to the correct table in the database.. I fail to see why this would be. Any help greatly appreciated. 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) { $row = mysqli_fetch_array($data); } ?> <?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 = '$username' WHERE user_id = '" . $row['user_id'] ."'"; }} else { $query = "UPDATE antique SET name = '$name', phone = '$phone', address1 = '$address1', address2 = '$address2', postcode = '$postcode', " . " email = '$email', webadd = '$webadd', username = '$username' WHERE user_id = '" . $row['user_id'] ."'"; } 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 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="address2">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> do you see anything wrong with this update code? i am having trouble setting the acntStatus=1. Code: [Select] <?php mysql_select_db($database_uploader, $uploader); $query = "SELECT * FROM members WHERE uname='$_SESSION[user]'"; $result = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result) or die(mysql_error()); $usedSpace = $row['bandwhitch']; $acntType = $row['acntType']; if ($acntType == 1) { $totalSpace = 500; } else { $totalSpace = 250; } if($usedSpace > $totalSpace) { echo "There is something wrong with your account. Please contact us!"; $usageError = true; mysql_query(sprintf("UPDATE members SET acntStatus='%s' WHERE uname='%d'", mysql_real_escape_string(1), $_SESSION['user'])) or die(mysql_error()); mysql_close($con); } $usagePercent = (round(($usedSpace/$totalSpace), 2)) * 100; // Convert to percentage } ?> Hey guys, I've been doing a little bit of exerementing with PDO's and it seems I can't get it to update the database... I don't know why... Anyway here is the code: index.php Code: [Select] <?php /** * @author Jragon * @copyright 2011 */ require_once('includes/include.php'); $user = new user(); $user->newUser('Jragon', 'blenders', $DBH); echo '=D'; ?> /includes/connect.inc.php Code: [Select] <?php /** * @author Jragon * @copyright 2011 */ //Define connection details //host define('HOST', 'localhost'); //DataBase define('DB', 'rankometer'); //Username define('USER', 'root'); //Password define('PASS', ''); ?> /includes/connect.php Code: [Select] <?php /** * @author Jragon * @copyright 2011 */ //Include connection crap require_once('connect.inc.php'); //connect try { //new PDO $DBH = new PDO("mysql:host=" . HOST . ";dbname=" . DB, USER, PASS); //check for errors } catch(PDOException $e) { echo $e->getMessage(); } ?> /classes/user.class.php Code: [Select] <?php /** * @author Jragon * @copyright 2011 */ class user{ private $username; private $password; private $newPassword; private $salt; private $DBH; public function newUser($user, $pass, $DBH){ //name varibles $this->password = $pass; $this->username = $user; $this->DBH = $DBH; $this->getSalt(); $this->hashPass(); $this->createUser(); } private function getSalt(){ //pick random number $a = rand(1, 100); $b = rand(1, 100); $this->salt = rand($a, $b) * 5; } private function hashPass(){ //encrypt $this->password with md5 and a salt $plainPass = $this->password . $this->salt; $this->newPassword = md5($plainPass); } private function createUser(){ //prepare statement $STH = $this->DBH->prepare(" INSERT INTO `users` ( `user` , `pass` , `salt` ) VALUES ( '$this->username', '$this->newPassword', '$this->salt' ); "); //execute statement $STH->execute(); //prepare statement $STH = $this->DBH->prepare(" INSERT INTO `ranks` ( `rank` ) VALUES ( ); "); //execute statement $STH->execute(); } } ?> SQL dump Code: [Select] -- phpMyAdmin SQL Dump -- version 3.3.9 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jun 02, 2011 at 06:05 PM -- Server version: 5.5.8 -- PHP Version: 5.3.5 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; -- -- Database: `cakes` -- -- -------------------------------------------------------- -- -- Table structure for table `cakes` -- CREATE TABLE IF NOT EXISTS `cakes` ( `UID` int(11) NOT NULL AUTO_INCREMENT, `cake` int(11) NOT NULL, PRIMARY KEY (`UID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -- Dumping data for table `cakes` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `UID` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(11) NOT NULL, `passWord` varchar(32) NOT NULL, `salt` int(11) NOT NULL, PRIMARY KEY (`UID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Dumping data for table `users` -- I have no idea what is going wrong... I don't get an error. All the output I get is '=D'. Thanks -Jragon Hi I am trying my first OOP update. I have it working exactly as I want except for one thing. For some reason if I try to update the database with the same information (every column exactly the same) it returns 0 affected rows. is there anyway of getting the database to update, even if all columns are exactly the same? Code: Code: [Select] $membershipID = Profile_membership::find_membership_ID($UID); $MID = $membershipID->id; $new_member = Profile_membership::make($MID, $UID, $acc_type, $membership, $upgradeL, $date, $dateUpgraded); if($new_member && $new_member->save()){ $flag = 1; }else{ $message .= "Error: Sorry, there was an error creating your membership. <br> Please try again<br>"; $flag = 0; } $new_member->save() will create the database entry if no ID exists, and will update if an ID does exist. So, I want the save() to return success. If it does, move on else give an error. However, I'm getting the error, if a user accidentally clicks submit, when no fields have been changed. I what it to still update, so $flag will be 1 Thanks |