PHP - Adding Info To Mysql Database
Hi Im having some trouble implementing info into a database
Similar Tutorialshello i am trying to add infomation into the mysql but it always seems to add it a 0 instead of what i am typeing into the form, the form is to add recipies to a users file. these are the scriprts, the fields that arnt showing up is prep and cook add_recipie.php <?php // Start_session, check if user is logged in or not, and connect to the database all in one included file include_once("scripts/checkuserlog.php"); // Include the class files for auto making links out of full URLs and for Time Ago date formatting include_once("wi_class_files/autoMakeLinks.php"); include_once ("wi_class_files/agoTimeFormat.php"); // Create the two objects before we can use them below in this script $activeLinkObject = new autoActiveLink; $myObject = new convertToAgo; ?> <?php // Include this script for random member display on home page include_once "scripts/homePage_randomMembers.php"; ?> <?php $sql_blabs = mysql_query("SELECT id, mem_id, the_blab, blab_date FROM blabbing ORDER BY blab_date DESC LIMIT 30"); $blabberDisplayList = ""; // Initialize the variable here while($row = mysql_fetch_array($sql_blabs)){ $blabid = $row["id"]; $uid = $row["mem_id"]; $the_blab = $row["the_blab"]; $notokinarray = array("fag", "gay", "shit", "fuck", "stupid", "idiot", "asshole", "cunt", "douche"); $okinarray = array("sorcerer", "grey", "shug", "farg", "smart", "awesome guy", "asshole", "cake", "dude"); $the_blab = str_replace($notokinarray, $okinarray, $the_blab); $the_blab = ($activeLinkObject -> makeActiveLink($the_blab)); $blab_date = $row["blab_date"]; $convertedTime = ($myObject -> convert_datetime($blab_date)); $whenBlab = ($myObject -> makeAgo($convertedTime)); //$blab_date = strftime("%b %d, %Y %I:%M:%S %p", strtotime($blab_date)); // Inner sql query $sql_mem_data = mysql_query("SELECT id, username, firstname, lastname FROM myMembers WHERE id='$uid' LIMIT 1"); while($row = mysql_fetch_array($sql_mem_data)){ $uid = $row["id"]; $username = $row["username"]; $firstname = $row["firstname"]; if ($firstname != "") {$username = $firstname; } // (I added usernames late in my system, this line is not needed for you) /////// Mechanism to Display Pic. See if they have uploaded a pic or not ////////////////////////// $ucheck_pic = "members/$uid/image01.jpg"; $udefault_pic = "members/0/image01.jpg"; if (file_exists($ucheck_pic)) { $blabber_pic = '<div style="overflow:hidden; width:40px; height:40px;"><img src="' . $ucheck_pic . '" width="40px" border="0" /></div>'; // forces picture to be 100px wide and no more } else { $blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" height=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more } $blabberDisplayList .= ' <table width="100%" align="center" cellpadding="4" bgcolor="#CCCCCC"> <tr> <td width="7%" bgcolor="#FFFFFF" valign="top"><a href="profile.php?id=' . $uid . '">' . $blabber_pic . '</a> </td> <td width="93%" bgcolor="#EFEFEF" style="line-height:1.5em;" valign="top"><span class="greenColor textsize10">' . $whenBlab . ' <a href="profile.php?id=' . $uid . '">' . $username . '</a> said: </span><br /> ' . $the_blab . '</td> </tr> </table>'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta name="Description" content="Web Intersect is a deft combination of powerful free open source software for social networking, mixed with insider guidance and tutorials as to how it is made at its core for maximum adaptability. The goal is to give you a free website system that has a network or community integrated into it to allow people to join and interact with your website when you have the need." /> <meta name="Keywords" content="web intersect, how to build community, build social network, how to build website, learn free online, php and mysql, internet crossroads, directory, friend, business, update, profile, connect, all, website, blog, social network, connecting people, youtube, myspace, facebook, twitter, dynamic, portal, community, technical, expert, professional, personal, find, school, build, join, combine, marketing, optimization, spider, search, engine, seo, script" /> <title>CookBookers</title> <link href="style/main.css" rel="stylesheet" type="text/css" /> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <script src="js/jquery-1.4.2.js" type="text/javascript"></script> <style type="text/css"> #Layer1 { height:210px; } body { background-color: #3c60a4; } .style4 {font-size: 36px} </style> </head> <body> <p> <?php include_once "header_template.php"; ?> </head> <body style="margin:0px;"> <center> </p> <p> </p> <table border="0" align="center" cellpadding="0" cellspacing="0" class="mainBodyTable"> <tr> <td width="124" valign="top"> <td width="776" colspan="2" align="left" valign="top" style="background-color:#EFEFEF; border:#999 0px; padding:10px;"> <table border="0" cellpadding="6"> </table> <table width="574" border="0"> <form method="POST" action="include/recipe.php"> <span class="style4">Add Recipie</span> <tr> <th width="232" scope="col"> </th> <th width="332" scope="col"> </th> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Public:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="Pub" value="1" type="checkbox" id="Pub"/> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Title:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="title" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Prep time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="prep" type="text" size="7" maxlength="10" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Cooking time:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input name="cook" type="text" size="7" maxlength="10" /> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Makes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <input type="text" name="make" /> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Ingrediants:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="ingr" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Method: </span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="desc" cols="40"></textarea> </span></td> </tr> <tr> <td><span style="margin-bottom:5px; color:brown;">Notes:</span></td> <td><span style="margin-bottom:5px; color:brown;"> <textarea rows="5" name="note" cols="40"></textarea> </span></td> </tr> <tr> <td><input name="submit" type="submit" style="padding:5px 10px;" value="Submit" /></td> </tr> </table> </tr> </table> </td> </tr> </table> <?php include_once "footer_template.php"; ?> </body> recipie.php <?php //include("session.php"); include("database.php"); @session_start(); $user = $_SESSION['username']; //die($user); $Pub=$_POST['Pub']; $title=$_POST['title']; $prep=$_POST['prep']; $cook=$_POST['cook']; $make=$_POST['make']; $ingr=$_POST['ingr']; $desc=$_POST['desc']; $note=$_POST['note']; //if($user=="Guest"||$user==""){ //header("Location: ../index.php"); //} //else{ $database->AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc,$note); header("Location: ../recipe_added.php"); //} ?> database.php <? /** * Database.php * * The Database class is meant to simplify the task of accessing * information from the website's database. * * Written by: Jpmaster77 a.k.a. The Grandmaster of C++ (GMC) * Last Updated: August 17, 2004 */ include("constants.php"); class MySQLDB { var $connection; //The MySQL database connection var $num_active_users; //Number of active users viewing site var $num_active_guests; //Number of active guests viewing site var $num_members; //Number of signed-up users /* Note: call getNumMembers() to access $num_members! */ /* Class constructor */ function MySQLDB(){ /* Make connection to database */ $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error()); mysql_select_db(DB_NAME, $this->connection) or die(mysql_error()); /** * Only query database to find out number of members * when getNumMembers() is called for the first time, * until then, default value set. */ $this->num_members = -1; if(TRACK_VISITORS){ /* Calculate number of users at site */ $this->calcNumActiveUsers(); /* Calculate number of guests at site */ $this->calcNumActiveGuests(); } } /** * confirmUserPass - Checks whether or not the given * username is in the database, if so it checks if the * given password is the same password in the database * for that user. If the user doesn't exist or if the * passwords don't match up, it returns an error code * (1 or 2). On success it returns 0. */ function confirmUserPass($username, $password){ /* Add slashes if necessary (for query) */ if(!get_magic_quotes_gpc()) { $username = addslashes($username); } /* Verify that user is in database */ $q = "SELECT password FROM ".TBL_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); if(!$result || (mysql_numrows($result) < 1)){ return 1; //Indicates username failure } /* Retrieve password from result, strip slashes */ $dbarray = mysql_fetch_array($result); $dbarray['password'] = stripslashes($dbarray['password']); $password = stripslashes($password); /* Validate that password is correct */ if($password == $dbarray['password']){ return 0; //Success! Username and password confirmed } else{ return 2; //Indicates password failure } } /** * confirmUserID - Checks whether or not the given * username is in the database, if so it checks if the * given userid is the same userid in the database * for that user. If the user doesn't exist or if the * userids don't match up, it returns an error code * (1 or 2). On success it returns 0. */ function confirmUserID($username, $userid){ /* Add slashes if necessary (for query) */ if(!get_magic_quotes_gpc()) { $username = addslashes($username); } /* Verify that user is in database */ $q = "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); if(!$result || (mysql_numrows($result) < 1)){ return 1; //Indicates username failure } /* Retrieve userid from result, strip slashes */ $dbarray = mysql_fetch_array($result); $dbarray['userid'] = stripslashes($dbarray['userid']); $userid = stripslashes($userid); /* Validate that userid is correct */ if($userid == $dbarray['userid']){ return 0; //Success! Username and userid confirmed } else{ return 2; //Indicates userid invalid } } /** * usernameTaken - Returns true if the username has * been taken by another user, false otherwise. */ function usernameTaken($username){ if(!get_magic_quotes_gpc()){ $username = addslashes($username); } $q = "SELECT username FROM ".TBL_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); return (mysql_numrows($result) > 0); } function showRecipees($username){ $q = "SELECT * FROM recipies WHERE user = '$username'"; $result = mysql_query($q, $this->connection); /* Error occurred, return given name by default */ if(!$result || (mysql_numrows($result) < 1)){ return NULL; } /* Return result array */ $rows; $i=0; while($row=mysql_fetch_row($result)) { $rows[$i]=$row; $i++; } return $rows; } function showRecipees1(){ $q = "SELECT * FROM recipies"; $result = mysql_query($q, $this->connection); /* Error occurred, return given name by default */ if(!$result || (mysql_numrows($result) < 1)){ return NULL; } /* Return result array */ $rows; $i=0; while($row=mysql_fetch_row($result)) { $rows[$i]=$row; $i++; } return $rows; } /** * usernameBanned - Returns true if the username has * been banned by the administrator. */ function usernameBanned($username){ if(!get_magic_quotes_gpc()){ $username = addslashes($username); } $q = "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); return (mysql_numrows($result) > 0); } /** * addNewUser - Inserts the given (username, password, email) * info into the database. Appropriate user level is set. * Returns true on success, false otherwise. */ function addNewUser($username, $password, $email){ $time = time(); /* If admin sign up, give admin user level */ if(strcasecmp($username, ADMIN_NAME) == 0){ $ulevel = ADMIN_LEVEL; }else{ $ulevel = USER_LEVEL; } $q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', $time)"; return mysql_query($q, $this->connection); } /** * updateUserField - Updates a field, specified by the field * parameter, in the user's row of the database. */ function updateUserField($username, $field, $value){ $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'"; return mysql_query($q, $this->connection); } /** * getUserInfo - Returns the result array from a mysql * query asking for all information stored regarding * the given username. If query fails, NULL is returned. */ function getUserInfo($username){ $q = "SELECT * FROM ".TBL_USERS." WHERE username = '$username'"; $result = mysql_query($q, $this->connection); /* Error occurred, return given name by default */ if(!$result || (mysql_numrows($result) < 1)){ return NULL; } /* Return result array */ $dbarray = mysql_fetch_array($result); return $dbarray; } /** * getNumMembers - Returns the number of signed-up users * of the website, banned members not included. The first * time the function is called on page load, the database * is queried, on subsequent calls, the stored result * is returned. This is to improve efficiency, effectively * not querying the database when no call is made. */ function getNumMembers(){ if($this->num_members < 0){ $q = "SELECT * FROM ".TBL_USERS; $result = mysql_query($q, $this->connection); $this->num_members = mysql_numrows($result); } return $this->num_members; } /** * calcNumActiveUsers - Finds out how many active users * are viewing site and sets class variable accordingly. */ function calcNumActiveUsers(){ /* Calculate number of users at site */ $q = "SELECT * FROM ".TBL_ACTIVE_USERS; $result = mysql_query($q, $this->connection); $this->num_active_users = mysql_numrows($result); } /** * calcNumActiveGuests - Finds out how many active guests * are viewing site and sets class variable accordingly. */ function calcNumActiveGuests(){ /* Calculate number of guests at site */ $q = "SELECT * FROM ".TBL_ACTIVE_GUESTS; $result = mysql_query($q, $this->connection); $this->num_active_guests = mysql_numrows($result); } /** * addActiveUser - Updates username's last active timestamp * in the database, and also adds him to the table of * active users, or updates timestamp if already there. */ function addActiveUser($username, $time){ $q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'"; mysql_query($q, $this->connection); if(!TRACK_VISITORS) return; $q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* addActiveGuest - Adds guest to active guests table */ function addActiveGuest($ip, $time){ if(!TRACK_VISITORS) return; $q = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } /* These functions are self explanatory, no need for comments */ /* removeActiveUser */ function removeActiveUser($username){ if(!TRACK_VISITORS) return; $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* removeActiveGuest */ function removeActiveGuest($ip){ if(!TRACK_VISITORS) return; $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } /* removeInactiveUsers */ function removeInactiveUsers(){ if(!TRACK_VISITORS) return; $timeout = time()-USER_TIMEOUT*60; $q = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout"; mysql_query($q, $this->connection); $this->calcNumActiveUsers(); } /* removeInactiveGuests */ function removeInactiveGuests(){ if(!TRACK_VISITORS) return; $timeout = time()-GUEST_TIMEOUT*60; $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout"; mysql_query($q, $this->connection); $this->calcNumActiveGuests(); } function AddRecipe($user,$Pub,$title,$prep,$cook,$make,$ingr,$desc, $note){ if(!TRACK_VISITORS) return; $q = "INSERT INTO recipies (`user` ,`Pub` ,`title` ,`prep` ,`cook` ,`makes` ,`ingredients` ,`recipe` ,`notes`)VALUES ('$user', '$Pub', '$title', 'prep', 'cook','$make', '$ingr', '$desc', '$note');"; mysql_query($q, $this->connection) or die(mysql_error()); $this->calcNumActiveGuests(); } function recipie_comment($user,$comment,$recipie_id){ if(!TRACK_VISITORS) return; $q = "INSERT INTO recipie_comment (`user` ,`comment`, `recipie_id`);"; mysql_query($q, $this->connection) or die(mysql_error()); $this->calcNumActiveGuests(); } /** * query - Performs the given query on the database and * returns the result, which may be false, true or a * resource identifier. */ function query($query){ return mysql_query($query, $this->connection); } }; /* Create database connection */ $database = new MySQLDB; ?> and also the fields in the database are int 11 for both prep and cook thanks Im trying to add some info to an existing cell in a mysql database. The cell currently reads: This is a piece of information. I would like to update the cell to read: This is a piece of information. a great piece of info. I have a variable with the following; $info = a great piece of info. Is it possible to add $info to the existing cell via php eg. <?php mysql_query("UPDATE mytable SET info = '$info' WHERE row = '$row'"); ?> all fine except I dont want to SET the info to $info I simply want to add $info onto the end of the existing data in the info record. Is this possible and how do i change the above query and go about it? Many thanks Hi there. I have this simple code which displays 5 results. How can i grab each element separately instead of displaying all the results at once. Thanks:) Code: [Select] <?php $query = mysql_query("SELECT product_name, product_price FROM products WHERE product_type = 'laptop' LIMIT 5"); $numrows = mysql_num_rows($query); if ($numrows != 0) { while ($row = mysql_fetch_assoc($query)) { $product_name = $row['product_name']; $product_price = $row['product_price']; echo $product_name . '<br />'; echo $product_price . '<br /><br />'; } } ?> well I know the standard way of retrieving mysql data was through the following codes: Code: [Select] $query = "SELECT * FROM {$tablename} WHERE columnmame = '{$var}'"; $result = mysql_query($query); $row = mysql_fetch_array($result); This will return all properties inside a table row by an associative array indexed by column names. I am, however, wondering if there is an easier way to retrieve database info from more than one table. For now, what I am doing is: Code: [Select] $result = mysql_query( "SELECT * FROM {$tablename} WHERE columnmame = '{$var}'"); $row = mysql_fetch_array($result); $result2 = mysql_query( "SELECT * FROM {$tablename2} WHERE columnmame2 = '{$var2}'"); $row2 = mysql_fetch_array($result2); which is a bit tedious and can cause problems when two or more coders work on the same project(it will be difficult to tell what is $row1, $row2 and $row3...). Is there away to write a simpler code than the one above? I mean, if it is possible to run mysql_fetch_array only once and retrieve database info from multiple tables? Hi there, I am using this code to send the users email address to the database. That works fine, but i keep getting blank info added to the database. Does anyone know how i can stop this? <?php $con = mysql_connect("*","*","*"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ogs_mailinglist1", $con); $sql="INSERT INTO mailinglist (email) VALUES ('$_POST[rec_email]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } mysql_close($con); ?> Thanks, Hi, I have a website where users can log on and edit their profile pic, name, biography etc. I was wondering about the correct way to:- Add data to the database through forms (Register.php) Display the data on a page Using mysql escape sting, however, the way I am currently using will display a '\' before any ' symbol. So it's >> it\'s ... Here is a snippet of the code I am using... Code: [Select] //insert data $about1 = mysql_real_escape_string($_POST['about']); //get $query = mysql_query("SELECT * FROM `staff` WHERE username='$username'"); $row = mysql_fetch_array($query); $about = $row['about']; echo $about; I am trying to set up a item entry page form.png: Upon submission it shows unsuccessful even though I have checked the fields on mysql table and seem to be good am I missing something? Code: [Select] <form action="" method="post" enctype="multipart/form-data" name="Product_Entry"> <TABLE> <TR> <TD>Product ID</TD><TD><input name="SKU_ProductID" value="<?php if (isset($_post['SKU_ProductID'])) echo $_POST['SKU_ProductID']; ?>" type="text" size="11" maxlength="11" /></TD> </TR> <TR> <TD>Merchant SKU ID</TD><TD><input name="SKU_MerchSKUID" value="<?php if (isset($_post['SKU_MerchSKUID'])) echo $_POST['SKU_MerchSKUID']; ?>" type="text" size="18" maxlength="30" /></TD> </TR> <TR> <TD>Game Title</TD><TD><input name="Game_Title" value="<?php if (isset($_post['Game_Title'])) echo $_POST['Game_Title']; ?>" type="text" size="40" maxlength="40" /></TD> </TR> <TR> <TD>Platform</TD><TD><input name="Platform" value="<?php if (isset($_post['Platform'])) echo $_POST['Platform']; ?>" type="text" size="20" maxlength="20" /></TD> </TR> <TR> <TD>Genre</TD><TD><input name="Genre" value="<?php if (isset($_post['Genre'])) echo $_POST['Genre']; ?>" type="text" size="11" maxlength="11" /></TD> </TR> <TR> <TD>Weight</TD><TD><input name="Weight" value="<?php if (isset($_post['Weight'])) echo $_POST['Weight']; ?>" type="text" size="7" maxlength="7" /></TD> </TR> <TR> <TD>Supplier</TD><TD><input name="Supplier" Value="<?php if (isset($_post['Supplier'])) echo $_POST['Supplier']; ?>" type="text" size="25" maxlength="25" /></TD> </TR> <TR> <TD>Suppliers Price</TD><TD><input name="Supplier_Price" value="<?php if (isset($_post['Supplier_Price'])) echo $_POST['Supplier_Price']; ?>" type="text" size="10" maxlength="12" /></TD> </TR> <TR> <TD>Cashback</TD><TD><input name="Cashback" value="<?php if (isset($_post['Cashback'])) echo $_POST['Cashback']; ?>" type="text" size="6" maxlength="8" /></TD> </TR> <TR> <TD>Cashback Amount</TD><TD><input name="Cashback_Amount" value="<?php if (isset($_post['Cashback_Amount'])) echo $_POST['Cashback_Amount']; ?>" type="text" size="7" maxlength="11" /></TD> </TR> <TR> <TD><input type="hidden" name="submitted" value="true"/></TD><TD><input name="Submit" type="submit" value="Add_Product" /></TD> </TR></form></TABLE> <?php # Product Entry $page_title = 'Product Entry'; if (isset($_POST['Submit'])) { $errors = array(); if (empty($_POST['SKU_ProductID'])) { $errors[] = 'Please enter Product ID.'; } else { $sid = trim($_POST['SKU_ProductID']); } if (empty($_POST['SKU_MerchSKUID'])) { $errors[] = 'Please enter Merchant SKU.'; } else { $mid = trim($_POST['SKU_MerchSKUID']); } if (empty($_POST['Game_Title'])) { $errors[] = 'Please enter Game Title.'; } else { $gt = trim($_POST['Game_Title']); } if (empty($_POST['Platform'])) { $errors[] = 'Please enter Platform.'; } else { $pl = trim($_POST['Platform']); } if (empty($_POST['Genre'])) { $errors[] = 'Please enter Genre.'; } else { $ge = trim($_POST['Genre']); } if (empty($_POST['Weight'])) { $errors[] = 'Please enter Weight.'; } else { $we = trim($_POST['Weight']); } if (empty($_POST['Supplier'])) { $errors[] = 'Please enter Supplier.'; } else { $sup = trim($_POST['Supplier']); } if (empty($_POST['Supplier_Price'])) { $errors[] = 'Please enter Supplier Price.'; } else { $sp = trim($_POST['Supplier_Price']); } if (empty($_POST['Cashback'])) { $errors[] = 'Please enter Cashback %.'; } else { $cb = trim($_POST['Cashback']); } if (empty($_POST['Cashback_Amount'])) { $errors[] = 'Please enter Cashback Amount.'; } else { $cba = trim($_POST['Cashback_Amount']); } if (empty($errors)) { require_once ('connect.php'); [b]$q = "INSERT INTO `Products` (`SKU_ProductID`, `SKU_MerchSKUID`, `Game_Title`, `Platform`, `Genre`, `Weight`, `Supplier`, `Supplier_Price`, `Cashback`, `Cashback_Amount`) VALUES ('$sid', '$mid', '$gt', '$pl', '$ge', '$we', '$sup', '$sp', '$cb', '$cba')"; $r = @mysql_query ($dbc, $q); if ($r) { // If it ran OK. // Print a message: echo '<h1>Thank you!</h1> <p>Product Inserted!</p><p><br /></p>'; } else { // If it did not run OK. // Public message: echo '<h1>System Error</h1> <p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>'; // Debugging message: echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $q . '</p>'; } // End of if ($r) IF. mysqli_close($dbc); // Close the database connection.[/b] // Include the footer and quit the script: include ('includes/footer.html'); exit(); } else { echo '<H1>Error!</H1> <p class="error">The Following error(s) occurred:<br />'; foreach ($errors as $msg) { echo " - $msg<br />\n"; } echo '</p><p>Please try again.</p><p><br /></p>'; } } ?> If there is anything else needed let me know Greetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> I have a standard form that displays users current data from a mysql database once logged in(code obtained from the internet). Users can then edit their data then submit it to page called editform.php that does the update. All works well except that the page does not display the updated info. Users have to first logout and login again to see the updated info. even refreshing the page does not show the new info. Please tell me where the problem is as i am new to php.
my form page test.php
<?PHP require_once("./include/membersite_config.php"); if(!$fgmembersite->CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } ?> <form action="editform.php?id_user=<?= $fgmembersite->UserId() ?>" method="POST"> <input type="hidden" name="id_user" value="<?= $fgmembersite->UserId() ?>"><br> Name:<br> <input type="text" name="name" size="40" value="<?= $fgmembersite->UserFullName() ?>"><br><br> Email:<br> <input type="text" name="email" size="40" value="<?= $fgmembersite->UserEmail() ?> "><br><br> Address:<br> <input type="text" name="address" size="40" value="<?= $fgmembersite->UserAddress() ?> "><br><br> <button>Submit</button>my editform.php <?php $con = mysqli_connect("localhost","root","user","pass"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"UPDATE fgusers3 SET name = '".$_POST['name']."', email= '".$_POST['email']."', address= '".$_POST['address']."' WHERE id_user='".$_POST['id_user']."'"); header("Location: test.php"); ?> Hi, I was wondering if this is possible as I've been tasked (uni project) with creating a blog site that displays entries in order of creation. From what I've seen, when modifying the file I can only add entries from the bottom line and not from the top without replacing the previously stored content. Thank you. Well, I have been able to create a registration and login page. Now I am trying to make an "Edit Profile" page but I can't seem to be able to pull up their primary key field which is called "userID" and I need help doing this. How would I get it from the MySQL database? Hello all, I have a directory page that is populated with a foreach loop pulling info from a db table. I want to make a "Download Directory pdf" button that will print out the directory entries in a nicely formatted way. The thing is that the foreach loop uses an OO call to what every template is being used for the HTML display: foreach ( (array) $results as $row) { ... $out .= '<div class="cn-list-row' . $alternate . ' vcard ' . $template->slug . ' ' . $entry->getCategoryClass(TRUE) . '">' . "\n"; $out = apply_filters('cn_entry_before', $out, $entry); ob_start(); include($template->file); $out .= ob_get_contents(); ob_end_clean(); $out = apply_filters('cn_entry_after', $out, $entry); $out .= '</div>' . "\n"; } $out .= '<div class="clear"></div>' . "\n"; $out .= '</div>' . "\n"; $out = apply_filters('cn_list_after', $out, $results); return $out; } Any Ideas?? I have created a form that i can see the form input info in to the form boxes but once submitted it is not updating or adding new input to the database. I am trying to keep it as simple as possible. I am also new at PHP.
Here is my code:
<?php // define variables and set to empty values $amp_20_parts_idErr = $part_numberErr = $locationErr = $quantityErr = ""; $amp_20_parts_id = $part_number = $discription = $location = $quantity = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["amp_20_parts_id"])) { $amp_20_parts_idErr = "ID is required."; } else { $amp_20_parts_id= test_input($_POST["amp_20_parts_id"]); } if (empty($_POST["part_number"])) { $part_numberErr = "Part number is required."; } else { $email = test_input($_POST["part_number"]); } if (empty($_POST["description"])) { $descriptionErr = ""; } else { $description = test_input($_POST["description"]); } if (empty($_POST["location"])) { $locationErr = "A location is required."; } else { $location = test_input($_POST["location"]); } if (empty($_POST["quantity"])) { $quantityErr = "Quantity is required"; } else { $quantity = test_input($_POST["quantity"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <div id="update_form"> Please follow instructions for updating the data base.<br>instructional text goes here.<br/><br/> <table><tr><form method="POST" action="new path"> <td>ID: <input name="amp_20_parts_id" type="text"><span><?php echo $amp_20_parts_idErr; ?></span><br/><br/></td> <td>Part Number: <input name="part_number" type="text"><span><?php echo $part_numberErr; ?></span><br/><br/></td> <td><label>Discription: <textarea name="description" rows="3" col="20"></textarea> <br/><br/></td> <td>Location: <input name="location" type="text"><span><?php echo $locationErr;?> </span><br/><br/></td> <td>Quantity: <input name="quantity" type="text"><span><?php echo $quantityErr; ?> </span><br/><br/></td><br/> <td><input type="submit"></td> </form></tr></table> <?php $con=mysqli_connect("server","user","password","db"); // Check connection if (mysqli_connect_errno()) { echo("Connect failed: %s\n", mysqli_connect_error()); // escape variables for security $amp_20_parts_id = mysqli_real_escape_string($con, $_POST['amp_20_parts_id']); $part_number = mysqli_real_escape_string($con, $_POST['part_number']); $discription = mysqli_real_escape_string($con, $_POST['description']); $location = mysqli_real_escape_string($con, $_POST['location']); $quantity = mysqli_real_escape_string($con, $_POST['quantity']); $sql="INSERT INTO amp_20 (amp_20_parts_id, part_number, description, location, quantity) VALUES ('$amp_20_parts_id', '$part_number', '$description', '$location', '$quantity')"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } echo "1 record added"; mysqli_close($con); } ?> I'm currently trying...struggling....to teach myself PHP and I'm really bugged with this database stuff. I am slowly managing but I'm a tad bit stuck now. I want to show a specific piece of information from a table. Lets say my table is structured like so: id user email 1 Bob Bob@Name.com 2 Fred Fred@Name.com 3 Matt Matt@Name.com What would I need to do to display ONLY Freds user? One way I tried only displayed the first rows info (Bob) the second way I tried (with a while loop) only displayed the last rows info (Matt) Heres my current code: <html> <body> <?php include 'dbwire.php'; $query = mysql_query('SELECT * FROM user'); $row = mysql_fetch_array($query); while ($row = mysql_fetch_array($query)) { echo '<b>User:</b> ' . $row['user'] . '<br />'; } ?> </body> </html> Hi, I'm working with sessions for the first time and have been able to put a member's id into the database. However, when I try and put their display name into the database I got a message saying Unknown column 'xyz' in 'field list' xyz was the display name for the session. Just can't seem to see what I'm doing wrong. In the code below, I even tried changing $_SESSION['member_display_name'] to $_SESSION['member_id'], in which case the correct id was inserted into both the member_id and the member_display_name fields in the database, so I know the table is set up correctly. Any tips? Code: [Select] //**********************SEND TO DATABASE**************************** include 'mysql_connect.php'; $query = "INSERT INTO uploads (date, member_id, upload_name, upload_title, upload_type, subject, topic, year, status, keywords, description, member_display_name, firstname, lastname)" . "VALUES (NOW(), ".$_SESSION['member_id'] . ",'$upload_nameX', '$upload_title', '".$EXPLODED_STRING[1]."', '$subject', '$topic', '$year', '$status', '$keywords', '$description', ".$_SESSION['member_display_name'] . ", '$firstname', '$lastname')"; //if($query){echo 'data has been placed'} mysql_query($query) or die(mysql_error()); $upload_id = mysql_insert_id(); //***********************END OF DATABASE CODE*********************** Sir/ma'am,
With the script I'm using to run my website, I've been trying to add an additional feature for the users to add/edit. I'll try to provide as much info as I can, hopefully it'll help.
Here is the code I'm using to display the user's unique info from the db.
<a class="wallet-edit"><?php echo $_SESSION['simple_auth']['INFO']?></a>That displays the user's info from the column 'INFO' perfectly. It's also a js popup to a menu to where I'm hoping to add a single textbox to edit the INFO. The script uses a similar function to edit the password with a popup. I've tried modifying the code to edit the INFO column but it doesn't work. Here is the default code it has to edit the password. I'm not sure if it can be changed to edit another column or needs a new piece of code for that. // user edit $('body').on('click', '.username-edit', function() { $('#modal').html(' '); var output = '<div class="modal-content"><h5><?php echo lang::get("Change password")?></h5><hr />'; output += '<h5><?php echo lang::get("New password:")?></h5><input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />'; output += '<h5><?php echo lang::get("Confirm password:")?></h5><input type="password" name="password2" id="password2" value="" class="text ui-widget-content ui-corner-all" />'; output += '</div>'; output += '<div class="modal-buttons right">'; output += '<button id="confirm-button" type="button" class="nice radius button"><?php echo lang::get("Change")?></button>'; output += '</div>'; output += '<a class="close-reveal-modal"></a>'; $('#modal').append(output); $('#second_modal').hide(); $('#modal').reveal(); $('#confirm-button').click(function(){ $('#password').css('border-color', '#CCCCCC'); $('#password2').css('border-color', '#CCCCCC'); var password = $('#password').val(); var password2 = $('#password2').val(); if(typeof(password) === 'undefined' || password == ''){ $('#password').css('border-color', 'red'); return false; } if(password != password2){ $('#password2').css('border-color', 'red'); return false; } password_data = encodeURIComponent(password); $.post("<?php echo gatorconf::get('base_url')?>", { changepassword: password_data} ).done(function(data) { // flush window.location.href = '<?php echo gatorconf::get('base_url')?>'; }); }); });If the code above can be edited to work with what I'm trying to do, it of course only needs one textbox and doesn't have to be confirmed by a second input. Please help! Thanks! My data input form is not working with the first few people who have tried to use it. I think it is because they are putting ' or " or some other character that is not allowed into the database. Any ideas how I can fix it? Hello I'm trying to set up a user area for my site where it displays the current logged in users ranking and other information in the future. <? ini_set('display_errors', 1); require_once "header.php"; $sql = "SELECT * FROM users WHERE username = ?"; if($stmt = mysqli_prepare($link, $sql)){ mysqli_stmt_bind_param($stmt, 's', $_SESSION['username']); if(mysqli_stmt_execute($stmt)){ $info = mysqli_fetch_array($stmt); echo "Current rank:" . $info['rank']; } else { echo "Can't find user"; } } mysqli_stmt_close($stmt); ?> That's the code I currently have but it gives me the error "but get an error message of mysqli_fetch_array() expects parameter 1 to be mysqli_result" I have two tables. Table Name:Users Fields: User_name user_email user_level pwd 2.Reference Fields: refid username origin destination user_name in the users table and the username field in reference fields are common fields. There is user order form.whenever an user places an order, refid field in reference table will be updated.So the user will be provided with an refid Steps: 1.User needs to log in with a valid user id and pwd 2.Once logged in, there will be search, where the user will input the refid which has been provided to him during the time of order placement. 3.Now User is able to view all the details for any refid 3.Up to this we have completed. Query: Now we need to retrieve the details based on the user logged in. For eg: user 'USER A' has been provided with the referenceid '1234' during the time of order placement user 'USER B' has been provided with the referenceid '2468' during the time of order placement When the userA login and enter the refid as '2468' he should not get any details.He should get details only for the reference ids which is assigned to him. Howdy, I'm trying to display text from a table in a database. It's a list of quotes, so I just need to pull out the quote and the author name. However, the quote and name are not fields in the same record; they are separate records. Example data: Code: [Select] quoteid name value 1 content You guys are great! Thanks for being awesome. 1 author John Jackson 2 content Gosh you're amazing! Always been so darn helpful! 2 author Peter Davis So, I just need to rip out the data from 'content' and 'author', and then group them together based on the quoteid. This is my code thus far: $testimonial_resource = mysql_query("SELECT name, value FROM quotes GROUP BY quoteid ORDER BY author ASC") or die(mysql_error()); while ($testimonial = mysql_fetch_assoc($testimonial_resource)) { echo '<p>'.$testimonial['value']'.<br /><strong>'.$testimonial['value'].'</strong></p>'; } Any help would be greatly appreciated for this novice. Cheers. |