PHP - Replace And Increment?
Hi there!
Hoping someone can help me with this very specific issue I have a string that looks like this: Code: [Select] var1 var2 X var3 var4 X var5 I need to find the highest number next to var (in this case 5), and to replace X with the following number (in this case var6). So after the replace, the string would look like this: Code: [Select] var1 var2 var6 (this x has been replaced for var6) var3 var4 var7 (this x has been replaced for var7) var5 Any ideas!? Thanks! Similar TutorialsThe situation is that I have a large string with some identifiers to say "replace me" with something else. My goal is to replace the values, but if one replacement includes one of the other keys, I don't want to replace it.
For example:
<?php $str = 'some blob ~abc~ followed by ~def~'; $arr_orig = array( '~abc~', '~def~' ); $arr_new = array( 'value~def~', 'blah' ); echo str_replace( $arr_orig, $arr_new, $str ); ?>This will echo: some blob valueblah followed by blah But that's not what I'm trying to accomplish. Basically, I want ~abc~ to be replaced with the literal: value~def~ and for the ~def~ that happens to be part of that string to NOT be replaced. I hope what I'm asking is clear. Basically, preg_replace/str_replace with arrays seems no different than just doing a FOR loop and replacing ~abc~ and then ~def~. But that's not what I need. I'm hoping that if ~abc~ is replaced with text that happens to be another identifier -- ~def~, ~xyz~, whatever -- that this already replaced text is not again replaced. Is there a built-in function to do something like this? If not, should I just parse the whole string and count characters or something? Seems like a pain (and slow!) Hi i wrote a find and replace code but my code replace last value of array and skip the first, second.... values in the array. Please give me an idea because i stack with this code. Regards $KeyWord = explode("\n", $RowGetWords['KEYWORDS']); $Replace = explode("\n", $RowGetWords['ReplaceTo']); for($i=0; $i<count($KeyWord); $i++){ $pattern = $KeyWord[$i]; $replace = "<a href=\"" .$URL. "\" target=\"_blank\" >" .$Replace[$i]. "</a>"; $html = str_replace($pattern, $replace, $Row['MessageBody']); } I believe it's called increment. Either way, I cannot figure out how to simply count up beginning at 1 (in red in the div below) ... function wp_rss( $url, $num_items = -1 ) { if ( $rss = fetch_rss( $url ) ) { echo '<div id="charts">'; if ( $num_items !== -1 ) { $rss->items = array_slice( $rss->items, 0, $num_items ); } foreach ( (array) $rss->items as $item ) { printf( '<div id="chart_lt">1</div><div id="chart_rt">%3$s</div>', esc_url( $item['link'] ), esc_attr( strip_tags( $item['description'] ) ), htmlentities( $item['title'] ) ); } echo '</div>'; } else { _e( 'An error has occurred, which probably means the feed is down. Try again later.' ); } } Code: [Select] $db->query('UPDATE users set actions=actions+1|'.time().' where id = '.$pun_user['id'].''); im trying to do set actions=actions+1, then put a | atfter +1ing it, then add my time stamp to it so I can explode it later. so it will look like this 2|unixtimestamphere how would i achieve this? or do I need to make another seperate row? seems dumb must be v easy to answer for many here but i dont know how to do it how can i use for loop to print values between any range but with increment of 0.5 0 0.5 1 1.5 2 2.5 3 ........till n I have a textfile called 'houses.txt': HA11QS, 200, house1.jpg, 4 HA22BR, 280, house2.jpg, 10 HA33AB, 390, house3.jpg, 3 HA44CD, 320, house4.jpg, 8 I have a php file which puts all this into an array and using a form, when the user enters a value e.g. 300 it, displays all the houses equal to or less than that. This works fine <?php if (isset($_POST['price'])) { $filename = "houses.txt"; $fileOpen = fopen($filename, "r"); $max = $_POST['price']; $rowsArr = file ($filename); foreach ($rowsArr as $row) { $lineDetails = $row; $item_array = explode (",", $row); if (((int) $item_array[1]) <= $max) { echo("<form action='visit.php' method='post'>"); echo("Post Code - " . $item_array[0]. "<br>"); echo("Price - " . $item_array[1]. ",000 <br>"); echo("Picture - " . $item_array[2]. "<br>"); echo("Number of Visits - " . $item_array[3]. "<br>"); echo("<input type='checkbox' name='mybox'>"); echo("<input type='submit' value='Visit Property'>"); echo("</form>"); } } fclose($fileOpen); } ?> However what i need to do is using a form, (Form values which i have just recently added to the code supplied above) Is that when a user clicks on property, it returns the house or houses selected with the checkboxes and the number of houses visits are incremented by 1 each time All i have is: <?php if (isset($_POST['mybox'])) { $filename = "houses.txt"; $fileOpen = fopen($filename, "r+"); $rowsArr = file ($filename); foreach ($rowsArr as $row) { $lineDetails = $row; $item_array = explode (",", $row); $house_visit = $item_array[3]; $house_visit++; echo("Post Code - " . $item_array[0]. "<br>"); echo("Price - " . $item_array[1]. ",000 <br>"); echo("Picture - " . $item_array[2]. "<br>"); echo("Number of Visits - " . $item_array[3]. "<br>"); echo("<br>"); } fclose($fileOpen); } ?> But it really doesnt work, if anyone can help me i would be grateful Thanks Hello, I am creating a job setup form and have a need for the job id field to increment based on the last inserted job id into our Oracle database. So far I have created a function that selects the maximum job id from the job table and adds 1 to the number. However, I run into the problem of when a user is filling out the form and another user opens it and begins filling out the form they both will receive the same job id in the field. I'm assuming this could possibly be solved with sessions, but I'm not sure where to start. Also, the form is not inserted into the table on submit (instead an excel sheet is created with the information and someone will enter the data into the database manually). Since the form data can be entered anytime from completion to next week/two weeks, how can I ensure that that job id is not used again. Thanks I'm wanting to increment usernames in ONLY the lowercase a-z for example if a user enters "abc" it will automatically be given "abc1" and the next user if entering the same username will automatically be given "abc2", the next "abc3" and so on. The base login and register script I'm using can be found on http://evolt.org/node/60265/ The database.php and register.php pages are below, but excluding the amendments I am seeking. I have created a MySQL database with 2 tables, 1 table named 'Users' with 3 columns named (1) 'userid' primary key, auto increment, (2) 'username' (3) 'password'. The other table is named 'UserCount' with 2 columns named (1) 'username' (2) 'count'. Can someone provide the PHP coding for the following process? When a new user registers a new username firstly PHP to check the characters are in lowercase a-z only and no other characters, and reject if they do not match, then for PHP to check to see if that username exists in the 'UserCount' table. If it doesn't exist, PHP to insert the new username into the 'username' column and also set the value of the 'count' column to 1. If the username does exist, PHP to add that username to the 'username' column and increment the value of the 'count' column by 1. Then in the 'Users' table PHP to insert a record with 'Users.username = UserCount.username + count' and PHP to inform the new user of their complete username including the integer that has been added to their first entered username. It would also help if I could be provided a link to a website on where I can better understand how to collate coding of this kind, coz I have tried to formulate this coding but as I'm playing around in the dark I have no idea if it is the right process in particular considering security factors. database.php Code: [Select] <?php /** * Connect to the mysql database. */ $conn = mysql_connect("localhost", "your_username", "your_password") or die(mysql_error()); mysql_select_db('your_database', $conn) or die(mysql_error()); ?> register.php Code: [Select] <?php session_start(); include("database.php"); /** * Returns true if the username has been taken * by another user, false otherwise. */ function usernameTaken($username){ global $conn; if(!get_magic_quotes_gpc()){ $username = addslashes($username); } $q = "select username from Users where username = '$username'"; $result = mysql_query($q,$conn); return (mysql_numrows($result) > 0); } /** * Inserts the given (username, password) pair * into the database. Returns true on success, * false otherwise. */ function addNewUser($username, $password){ global $conn; $q = "INSERT INTO Users VALUES ('$username', '$password')"; return mysql_query($q,$conn); } /** * Displays the appropriate message to the user * after the registration attempt. It displays a * success or failure status depending on a * session variable set during registration. */ function displayStatus(){ $uname = $_SESSION['reguname']; if($_SESSION['regresult']){ ?> <h1>Registered!</h1> <p>Thank you <b><?php echo $uname; ?></b>, your information has been added to the database, you may now <a href="main.php" title="Login">log in</a>.</p> <?php } else{ ?> <h1>Registration Failed</h1> <p>We're sorry, but an error has occurred and your registration for the username <b><?php echo $uname; ?></b>, could not be completed.<br> Please try again at a later time.</p> <?php } unset($_SESSION['reguname']); unset($_SESSION['registered']); unset($_SESSION['regresult']); } if(isset($_SESSION['registered'])){ /** * This is the page that will be displayed after the * registration has been attempted. */ ?> <html> <title>Registration Page</title> <body> <?php displayStatus(); ?> </body> </html> <?php return; } /** * Determines whether or not to show to sign-up form * based on whether the form has been submitted, if it * has, check the database for consistency and create * the new account. */ if(isset($_POST['subjoin'])){ /* Make sure all fields were entered */ if(!$_POST['user'] || !$_POST['pass']){ die('You didn\'t fill in a required field.'); } /* Spruce up username, check length */ $_POST['user'] = trim($_POST['user']); if(strlen($_POST['user']) > 30){ die("Sorry, the username is longer than 30 characters, please shorten it."); } /* Check if username is already in use */ if(usernameTaken($_POST['user'])){ $use = $_POST['user']; die("Sorry, the username: <strong>$use</strong> is already taken, please pick another one."); } /* Add the new account to the database */ $md5pass = md5($_POST['pass']); $_SESSION['reguname'] = $_POST['user']; $_SESSION['regresult'] = addNewUser($_POST['user'], $md5pass); $_SESSION['registered'] = true; echo "<meta http-equiv=\"Refresh\" content=\"0;url=$HTTP_SERVER_VARS[PHP_SELF]\">"; return; } else{ /** * This is the page with the sign-up form, the names * of the input fields are important and should not * be changed. */ ?> <html> <title>Registration Page</title> <body> <h1>Register</h1> <form action="<?php echo $HTTP_SERVER_VARS['PHP_SELF']; ?>" method="post"> <table align="left" border="0" cellspacing="0" cellpadding="3"> <tr><td>Username:</td><td><input type="text" name="user" maxlength="30"></td></tr> <tr><td>Password:</td><td><input type="password" name="pass" maxlength="30"></td></tr> <tr><td colspan="2" align="right"><input type="submit" name="subjoin" value="Join!"></td></tr> </table> </form> </body> </html> <?php } ?> I have tables in my MySQL database called "games", "wins" and "losses". I'm attempting to write SQL queries that will increment or decrement a value depending on what link is clicked from the main page. My SQL queries are as follows: <?php require_once('config.php'); if ( !isset($_SESSION['user']) ) { include('login.php'); exit; } $sql = 'select * from `teams` WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; $res = mysql_query($sql); //if ( mysql_num_rows($res) == 0 ) { include('index.php'); exit; } $row_team = mysql_fetch_array($res); if ( isset($_GET['addgame']) ) { $sql = 'UPDATE `teams` SET `games` = `games` + 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['subtractgame']) ) { $sql = 'UPDATE `teams` SET `games` = `games` - 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['addwin']) ) { $sql = 'UPDATE `teams` SET `wins` = `wins` + 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['subtractwin']) ) { $sql = 'UPDATE `teams` SET `wins` = `wins` - 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['addloss']) ) { $sql = 'UPDATE `teams` SET `losses` = `losses` + 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } if ( isset($_GET['subtractloss']) ) { $sql = 'UPDATE `teams` SET `losses` = `losses` - 1 WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; mysql_query($sql); } $sql = 'select * from `teams` WHERE `id` = \'' . mysql_real_escape_string($_GET['team']) . '\''; $res = mysql_query($sql); $row_team = mysql_fetch_array($res); ?> For some reason, I can increment the amount of games, wins or losses as many times as I want.. it'll be updated in the database and the changes will be reflected on the page. However, when I go to subtract a game, win or loss, it seems to leave null values as if there are no games, wins or losses at all. For example, say the site outputs the Yankees have 10 wins and 2 losses. When "[Add Win]" is clicked, the win total will increase to 11 and such changes will be displayed on the site. But, when "[Deduct Win]" is clicked, it seems to cancel out every value for the number of games, wins and losses and just outputs nothing.. Is there a reason for this? My addition is working fine, it's the subtraction that's messed up.. but it should work based on what I see. Thanks. Hey, In my table, I have 773 rows like this: 10800 ... 772 ... 771 ... 770 ... 769 ... etc ... When I insert a new row, it will have an ID of 10801 and not 773. I delete row 10800 and I want to insert a new row that has an ID of 773. Is there a code I can use also so that it creates the IDs in order? 1, 2, 3 etc no missing numbers. Thanks. Hi All, I have a rudimentary PHP page that displays a quote a day (366 quotes) from a text file. I have implemented sessions and javascript to account for the users time offset and this seems to be working well. As this is going to be for a iPhone mobile web app, I don't have to worry about DST or users having their computers time set incorrectly (the time is set automatically via cell towers by the service providers) The challenge now is that I would like to be able add Next and Previous links which would allow users to view a quote of the day from past and future dates. I have tried to implement it using the GET parameter like this: Code: [Select] // get day settings $day = (int) ($_GET['day'] ? $_GET['day'] : date('z')); // next quote link echo $next_quote_link = '<a href="?day='.($day != 366 ? $day + 1 : 1).'">Next Quote >></a>'; // previous quote link echo $previous_quote_link = '<a href="?day='.($day != 1 ? $day - 1 : 366).'"><< Previous Quote</a>'; but it seems to just return the same quote and date. Can someone help me figure out what I've overlooked or need to do to pass the date to the script correctly? Any help is appreciated Thanks in advance, kaiman Here is the complete script so far: Code: [Select] <?php // start session session_start(); // get timezone offset if(!isset($_SESSION['timezone'])) { if(!isset($_REQUEST['offset'])) { ?> <script type="text/javascript"> var d = new Date() var offset= -d.getTimezoneOffset()/60; location.href = "<?php echo $_SERVER['PHP_SELF']; ?>?offset="+offset; </script> <?php } else { $zonelist = array('Kwajalein' => -12.00, 'Pacific/Midway' => -11.00, 'Pacific/Honolulu' => -10.00, 'America/Anchorage' => -9.00, 'America/Los_Angeles' => -8.00, 'America/Denver' => -7.00, 'America/Tegucigalpa' => -6.00, 'America/New_York' => -5.00, 'America/Caracas' => -4.30, 'America/Halifax' => -4.00, 'America/St_Johns' => -3.30, 'America/Argentina/Buenos_Aires' => -3.00, 'America/Sao_Paulo' => -3.00, 'Atlantic/South_Georgia' => -2.00, 'Atlantic/Azores' => -1.00, 'Europe/Dublin' => 0, 'Europe/Belgrade' => 1.00, 'Europe/Minsk' => 2.00, 'Asia/Kuwait' => 3.00, 'Asia/Tehran' => 3.30, 'Asia/Muscat' => 4.00, 'Asia/Yekaterinburg' => 5.00, 'Asia/Kolkata' => 5.30, 'Asia/Katmandu' => 5.45, 'Asia/Dhaka' => 6.00, 'Asia/Rangoon' => 6.30, 'Asia/Krasnoyarsk' => 7.00, 'Asia/Brunei' => 8.00, 'Asia/Seoul' => 9.00, 'Australia/Darwin' => 9.30, 'Australia/Canberra' => 10.00, 'Asia/Magadan' => 11.00, 'Pacific/Fiji' => 12.00, 'Pacific/Tongatapu' => 13.00); $index = array_keys($zonelist, $_REQUEST['offset']); $_SESSION['timezone'] = $index[0]; } } // store timezone offset in session date_default_timezone_set($_SESSION['timezone']); ?> <html> <head> </head> <body> <?php // display the date echo "<h3>\n"; echo date("l, F jS, Y\n"); echo "</h3>\n"; // display the quote $lines = file("quotes.txt"); $day = date("z"); echo "<p>“".$lines[$day]."”<p>\n"; ?> </body> </html> Hey! I am making a comment system for my blog I'm making. The way I want it, is that when a comment is posted, it grabs the id of the post it's referring to, then creates a file called comment(POST ID HERE).txt.. I have that down, however I cannot for the life of me figure out how I can make it an increment, so it can make no more than 500, but everytime a comment is posted it will keep making the files go up like: comment1.txt comment2.txt comment3.txt Etc... Thanks very much, happy holidays! I have a db with entries as follows: A001 A002 A003 I would like to loop thru these and print them on screen. Instead of doing: echo A001 echo A002 echo A003 I'd like to find a better way since this database will scale up in the future and may get to A999. Is there a way to increment with leading placeholder zeros? for($x=0 ; $x < mysql_num_rows($myresult) ; $x++){ echo $row['A'.##increment here##']; } Thanks! Hi, I have coded a lot in the past but only now getting into PHP and web coding in general, when I use a while loop in most other languages I need to increment some form of counter to move to the next item e.g. Code: [Select] while (count < 10) { Do something; count + 1; } I am going through a set of tutorials that have just enlightened me to the following code when looking up a MYsql d'base: Code: [Select] $reults = "SELECT * FROM table"; while ($row = mysql_fetch_assoc($results)){ extract($row); echo $tblcol1; echo " - "; echo $tblcol2; echo "<br>"; } Now in fairness I have no real problem with this, if thats how you extract your results from a query then fine but I feel I am missing something and have not been able to nail it on the head. Am I to assume that $row in the loop returns the first row from the query results, moves through the actions of the loop, returns then automatically points to the next row of the array? Does that mean while($row){} where $row is a 3x3 array(for example) it would loop through this 3 times assigning the next row until the end? Is there a better way to explain this? ok this may not be able to be done .... but here goes nothing ... i have a roster that displays member names as a link to thier profile using a form and onclick submit() now what i didnt realize is that the form name will have to increment for each record returned from the query. i am by no means a guru with php so i need some help adding the foreach statement and setting the form name to increment each time what i need: I need this to automatically go +1 for each record returned Code: [Select] <form name="view3" action="./viewinfo.php" method="post"> <a href="#" onclick="document['view3'].submit()"> and i need the correct way to use the foreach statement ... i have read the manual and it just confuzzeled me . here is what i have so far. <?php include './clan_new/config.php'; include './clan_new/access.php'; $db = mysql_connect ($hostname, $username, $password) or die ('Failed to connect to database: ' . mysql_error()); mysql_select_db($database); $query = "SELECT * FROM $member_table WHERE $member_table.rank = 6 ORDER BY $member_table.name ASC"; $result = mysql_query($query) or die ('Failed to query ' . mysql_error()); while ($row = mysql_fetch_assoc($result)) { $steamid = $row['authid']; $name = $row['name']; $email = $row['email']; $fid = $row['fid']; $avatar = $row['avatar']; echo "<tr>"; if ($avatar==""){ echo "<td> </td>"; } else{ echo "<td><img height='35' width='35' src='./clan_new/avatars/$avatar'></td>"; } ?> <form name="view3" action="./viewinfo.php" method="post"> <input type="hidden" id="authid" name="authid" value="<?php echo "$steamid" ; ?>" /> </form> <td align="center"><a href="#" onclick="document['view3'].submit()"> <?php echo "$name" ; ?></a></td> <?php echo "<td align=\"center\"><a class=\"style2\" href=\"mailto:$email\" class=\"style2\">$email</a></td>"; if ($fid==""){ echo ""; } else{ echo "<td align=\"center\">+<a class=\"style2\" href=\"steam://friends/add/$fid\">Friend</a></td>"; } echo "</tr>"; } mysql_free_result($result); mysql_close($db); ?> Hi all.
In my database, i have a table where a client chose a service providers to make payments and each bill setup counts as a reward point for the client. Each bill counts as a single point even if the bill is edited after a services might have expired or renewed it should not be counted again as point.
to count the number of bill set up by a client i did
$stmt = $pdo->prepare("UPDATE reward_points SET num_bill = num_bill + 1 WHERE username = '$username' AND acct_num = '$acct_num'"); $stmt->execute();Its okay if it counts for new bills but i want it not to count for the same service provide and so i did $stmt=$pdo->query("SELECT company FROM payment WHERE username = '$username' AND trans_ref = '$trans_ref'"); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $coy = $row['company']; } //ps: note, $company is a variable from the form if(strcmp($coy, $company) == 0){ $stmt = $pdo->prepare("UPDATE reward_points SET num_bill = num_bill + 0 WHERE username = '$username' AND acct_num = '$acct_num'"); $stmt->execute(); }elseif(strcmp($coy, $company) != 0){ $stmt = $pdo->prepare("UPDATE reward_points SET num_bill = num_bill + 1 WHERE username = '$username' AND acct_num = '$acct_num'"); $stmt->execute(); }it just wont add up i also tried $coy1 = $coy; $coy2 = $company; $point = 0; if(strcmp($coy1, $coy2) == 0){ $add_point = $point + 0; }else{ $add_point = $point + 1; } $stmt = $pdo->prepare("UPDATE reward_points SET num_bill = $add_point WHERE username = '$username' AND acct_num = '$acct_num'"); $stmt->execute();still wont work. any idea? ok, how do I add an auto incremented value to another table at the same time the value is created. so I will do a query to insert into db, and it creates auto incremented value of 1, then I need this value to also be put into another table just as text. how do I go about doing this? I need this all in one query. hi .. i am working on chat system ..there are two types of user one are register and other are guest and i have to add guest user..in to database as temporary so they can chat with each other the problem i am facing is with there names i want name like this (Guest1,Guest2,Guest3,Guest4,...so on..)..i am trying but it is not working on live server .. i have tested it on my local server using xampp server.. it worked but not on live server... here is the code which i am using if(isset($_SESSION['Guest'])) { $_SESSION['Guest']=$_SESSION['Guest']+1; } else { $_SESSION['Guest']=1; and one more thing how i can delete Guest users who are not online.. is there a way to save a field in a session or variable while its being inserted into the data base? with out having to select it using another query $mail2 = "INSERT INTO pm SET pm_id = '', (turn pm_id into a $variable or session) WHERE blah blah blah the problem im having is Im creating two rows right after each other where each row is in differant tables and I need them to match ids and I have nothing to compare it to. only option i can think of is making a fast toggle switch or telling my select to grab in order which would work. SET UP: Windows vista # XAMPP 1.7.3, # Apache 2.2.14 (IPv6 enabled) + OpenSSL 0.9.8l # MySQL 5.1.41 + PBXT engine # PHP 5.3.1 # phpMyAdmin Problem: The name_id column from the card_numbers table doesn't increment at all. Even if if I put in two rows of data I'm left with the name_id not increasing. Main Goal: I want that column to increment with the same values as the other tables. Code for Mysql database: <?php require 'db.inc.php'; $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Unable to connect. Check your connection parameters.'); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); $query = 'CREATE TABLE IF NOT EXISTS subscriptions ( name_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, email_address VARCHAR(50), membership_type VARCHAR(50), PRIMARY KEY (name_id) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); // create the user information table $query = 'CREATE TABLE IF NOT EXISTS site_user_info ( name_id INTEGER UNSIGNED NOT NULL, terms_and_conditions VARCHAR(50) NOT NULL, name_on_card VARCHAR(50), credit_card_number VARCHAR(50), FOREIGN KEY (name_id) REFERENCES subscriptions(name_id) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); $query = 'CREATE TABLE IF NOT EXISTS card_numbers ( name_id INTEGER UNSIGNED NOT NULL, credit_card_expiration_data VARCHAR(50), FOREIGN KEY (name_id) REFERENCES subscriptions(name_id) ) ENGINE=MyISAM'; mysql_query($query, $db) or die (mysql_error($db)); echo 'Success!'; ?> Code of the data being inserted into mysql from forms: <?php //let's start our session, so we have access to stored data session_start(); session_register('membership_type'); session_register('terms_and_conditions'); include 'db.inc.php'; $db = mysql_connect('localhost', 'root', '') or die ('Unable to connect. Check your connection parameters.'); mysql_select_db('ourgallery', $db) or die(mysql_error($db)); //let's create the query $query = sprintf("INSERT INTO subscriptions ( name_id, name, email_address, membership_type) VALUES ('%s','%s','%s','%s')", name_id, mysql_real_escape_string($_SESSION['name']), mysql_real_escape_string($_SESSION['email_address']), mysql_real_escape_string($_SESSION['membership_type'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); $name_id = mysql_insert_id(); $query = sprintf("INSERT INTO site_user_info ( name_id, terms_and_conditions, name_on_card, credit_card_number ) VALUES ('%s','%s','%s','%s')", mysql_insert_id(), mysql_real_escape_string($_SESSION['terms_and_conditions']), mysql_real_escape_string($_POST['name_on_card']), mysql_real_escape_string($_POST['credit_card_number'])); //let's run the query $result = mysql_query($query, $db) or die(mysql_error($db)); $name_id = mysql_insert_id(); $query = sprintf("INSERT INTO card_numbers ( name_id, credit_card_expiration_data) VALUES ('%s','%s')", mysql_insert_id(), mysql_real_escape_string($_POST['credit_card_expiration_data'])); $result = mysql_query($query, $db) or die(mysql_error($db)); echo '$result'; ?> Should I be JOINING these tables together? I don't want the IDs to get muddled up otherwise it will screw up my database. |