PHP - Converting A Script To Work With A Database.
Hi, i'm basically having problems with this code, its for a newsletter script which added the email address into a file, i'm trying to convert it to work with mysql but having a few problems;
I've edited the last bit, the code just basically doesn't add it to the database even though i thought i had done it right... any help is very much appreciated! If email is not valid the script is letting me know; if email is valid it says "already added to the list" no matter what. old script <?php /** BY WebResourcesDepot - http://www.webresourcesdepot.com*/ /** YOU CAN EDIT HERE*/ $newsletterFileName = "file.txt"; /** IMPORTANT: EDIT BELOW UNLESS YOU KNOW WHAT YOU ARE DOING*/ function GetField($input) { $input=strip_tags($input); $input=str_replace("<","<",$input); $input=str_replace(">",">",$input); $input=str_replace("#","%23",$input); $input=str_replace("'","`",$input); $input=str_replace(";","%3B",$input); $input=str_replace("script","",$input); $input=str_replace("%3c","",$input); $input=str_replace("%3e","",$input); $input=trim($input); return $input; } /**Validate an email address. Provide email address (raw input) Returns true if the email address has the email address format and the domain exists. */ function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { // local part length exceeded $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } } return $isValid; } $email = GetField($_GET['email']); $pass = validEmail($email); if ($pass) { $f = fopen($newsletterFileName, 'a+'); $read = fread($f,filesize($newsletterFileName)); If (strstr($read,"@")) { $delimiter = ";"; } if (strstr($read,$email)) { echo 3; } else { fwrite($f, $delimiter . $email); echo 1; } fclose($f); } else { echo 2; } ?> edited script <?php /** BY WebResourcesDepot - http://www.webresourcesdepot.com*/ /** YOU CAN EDIT HERE*/ $newsletterFileName = "file.txt"; /** IMPORTANT: EDIT BELOW UNLESS YOU KNOW WHAT YOU ARE DOING*/ function GetField($input) { $input=strip_tags($input); $input=str_replace("<","<",$input); $input=str_replace(">",">",$input); $input=str_replace("#","%23",$input); $input=str_replace("'","`",$input); $input=str_replace(";","%3B",$input); $input=str_replace("script","",$input); $input=str_replace("%3c","",$input); $input=str_replace("%3e","",$input); $input=trim($input); return $input; } /**Validate an email address. Provide email address (raw input) Returns true if the email address has the email address format and the domain exists. */ function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { // local part length exceeded $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } } return $isValid; } $email = GetField($_GET['email']); $pass = validEmail($email); if ($pass) { $user_name = "_db"; $password = ""; $database = "_db"; $server = "localhost"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL2 = "SELECT * FROM newsletter WHERE email = '$_GET[email]'"; $result = mysql_query($SQL2); mysql_close($db_handle); } if (strstr($SQL2,$email)) { echo 3; } else { $user_name = "_db"; $password = ""; $database = "_db"; $server = "localhost"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "INSERT INTO newsletter (email,subscribed) VALUES ('$_GET[email]',1)"; $result = mysql_query($SQL); mysql_close($db_handle);} echo 1; } } else { echo 2; } ?> Similar TutorialsHi all, Thanks for reading. I'm hella frustrated at this script I wrote: for some reason, it will not work correctly. Basically, it works. The first 4 names in the table on the database show up when searched. But, anything past these four names in the database will not show up as a result when searched! I'm pulling my hair out here! It's really simple - take a gander: Code: [Select] if (isset($_POST['submit'])) { $search = $_POST['search']; $searchQuery = mysql_query("SELECT * FROM Accounts WHERE FullName='$search'"); if (mysql_num_rows($searchQuery) == 0) { $result = "Your search returned no results. Please try again."; } else { $results = 1; while ($getSearchResults = mysql_fetch_array($searchQuery)) { $fullName = $getSearchResults['FullName']; $result = "Name: ".$fullName.""; } } } ?> ...and the HTML form... Code: [Select] <form action="search.php" method="post"> <p>Search: <input type="text" name="search" size="35" maxlength="100" /></p> <p><input type="submit" value="Search" name="submit" /></p> <?php echo $result; ?> </form> Does anyone have any ideas? Hello everyone, I am trying to convert dates directly from the database but still keep it within the same array so that I can conveniently access it later on. I am not sure how to explain this better, but I believe the code is pretty self explanatory: $stmt = $this->db->query("SELECT title,slug,content,author_id,created FROM article"); $stmt->setFetchMode(PDO::FETCH_ASSOC); $i = 0; while($var = $stmt->fetch()) { $this->data[] = $var; $this->data[$i]['date'] = date("F j, Y", strtotime($var['created'])); $i++; } print_r($this->data); /* produced array Array ( [0] => Array ( [title] => PHP Security Book [slug] => php-security-book [content] => Lorem ipsum dolor sit amet, consectetur adipisicing elit. [author_id] => 3 [created] => 2012-03-13 12:34:42 [date] => March 13, 2012 ) [1] => Array ( [title] => Something To Do [slug] => somthing-to-do [content] => You know what a dolor sit amet, consectetur adipisicing elit. [author_id] => 3 [created] => 2012-03-13 12:35:46 [date] => March 13, 2012 ) ) */ I access it like so: foreach ($_data as $var) { echo '<h2>' . $var['title'] . '</h2> <br />'; echo '<b>' . $var['date'] . '</b> <br />'; echo '<p>' . $var['content'] . '</p> <br />'; } It works perfectly but my question is: Is there a better or more efficient way to do this? I think that my while loop could use some improvement. I was also thinking of maybe fetching the results into a class using PDO::FETCH_CLASS, but it seems like a bit of a hassle for just one modification. Say I have two functions that convert from Dollar to Cents and Cents to Dollar. function convertToDollar($value) { $amount = $value / 100; return $amount; } function convertToCents($value) { $amount = $value * 100; return $amount; } Currently I convert all the Dollar amounts to cents and store the cents in the mysql database column. When I showcase those amounts on a page, I simply convert the Cents back to Dollar. Am I doing this correctly or is there a better way to store product pricing in mysql table? Hey people, First post but i have visited for a while. I have the following HTML form which basically submits the $_session stored variables to PayPal. Advantage being that the user then doesn't need to re-enter their personal info at paypal. Code: [Select] <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_ext-enter"> <input type="hidden" name="redirect_cmd" value="_xclick"> <input type="hidden" name="business" value="myemailaddress@business.com"> <input type="hidden" name="item_name" value="myitem"> <input type="hidden" name="currency_code" value="GBP"> <input type="hidden" name="amount" value="<? echo $_SESSION['price']; ?>"> <input type="hidden" name="email" value="<? echo $_SESSION['email']; ?>"> <input type="hidden" name="first_name" value="<? echo $_SESSION['fname']; ?>"> <!--the rest of my fields --> <input type="hidden" name="currency_ code" value="GBP"> <input type="hidden" name="country" value="GB"> <input type="submit" class="buybtn" value=""> </form> Problem is i need to also submit some data to a database when the buy button is clicked and i cant have a form with two actions - therefore i need to change from what i have above to the form action being "paypal.php". That paypal.php script needs to do 2 things: 1) submit some data to my mysql database (that part i can do) and 2) submitting some &_session data to the paypal url (https://www.paypal.com/cgi-bin/webscr) just the same as the HTML form does...and take the user to that url...how do i do this? lol. I have no idea where to start in converting the below portion of the above form into a php code that a) submits to a url and (rather than a database) and b) redirects the user to that same url: Code: [Select] <input type="hidden" name="cmd" value="_ext-enter"> <input type="hidden" name="redirect_cmd" value="_xclick"> <input type="hidden" name="business" value="myemailaddress@business.com"> <input type="hidden" name="item_name" value="myitem"> <input type="hidden" name="currency_code" value="GBP"> <input type="hidden" name="amount" value="<? echo $_SESSION['price']; ?>"> <input type="hidden" name="email" value="<? echo $_SESSION['email']; ?>"> <input type="hidden" name="first_name" value="<? echo $_SESSION['fname']; ?>"> <!--the rest of my fields --> <input type="hidden" name="currency_ code" value="GBP"> <input type="hidden" name="country" value="GB"> Any help anyone can give me will be massively appreciated! Thanks everyone, Bill. I found this nice search database script on line but the pagination does not work can someone tell me what is wrong with it ???? so i can work with it !!! here is the full code : Code: [Select] <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","username","password"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("database") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "select * from the_table where 1st_field like \"%$trimmed%\" order by 1st_field"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; echo "<p><a href=\"http://www.google.com/search?q=" . $trimmed . "\" target=\"_blank\" title=\"Look up " . $trimmed . " on Google\">Click here</a> to try the search on google</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> Hello Community, maybe I'm a little bit over-worked, but I'm stucked in a problem with recursive database queries. I have a DB table with from/to relations. Here is an excerpt for only one relation (from rel_item_id_from=3 to rel_item_id_to=3): rel_id rel_item_id_from rel_item_id_to 1 52 3 2 3 17 My question is: How can I get a recursive solution to get the upward and downward children? It is also possible to have multiple relations (1:n or n:m). Thanks for your assistance - OLK I am having a big problem in MySQL and a part in my PHP coding as well. I created a registration form, where the user will have to fill his names, email address, choose a username and so on. I do not want duplicate email address and username in my database, thus, if a user choose either an email address or a username which has already taken, he will be notified. To prevent this duplication, I have set both the email address and username fields as UNIQUE KEY in MySQL. My problems a Even by setting both the username and email address fields as UNIQUE KEY, it is not working as I can register using the same email address or username. How to solve this? I have coded also to prevent this problem of duplicate so that the user will be notified to choose another email or username, but I am having a warning. My PHP codes: Code: [Select] <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (isset($_POST['fname']) && isset($_POST['lname'])&& isset($_POST['emailr']) && isset($_POST['user']) && isset($_POST['pass'])) { //Assignng variables $firstname = mysql_real_escape_string($_POST['fname']); $lastname = mysql_real_escape_string($_POST['lname']); $email = mysql_real_escape_string($_POST['emailr']); $uname = mysql_real_escape_string($_POST['user']); $pwd = mysql_real_escape_string($_POST['pass']); $pmd= md5($pwd); //Database $connect = mysql_connect('localhost', 'root', '') or die ('Connection Failed'); mysql_select_db('registration', $connect) or die ('Connection Failed'); //Registration codes if (empty($firstname) || empty($lastname) || empty($email) || empty($uname) || empty($pmd)) { echo '<p class="error">All fields are required to fill!</p>'; return false; } elseif (strlen($firstname) && (strlen($lastname) < '2')) { echo '<p class="error">Invalid first name or last name!</p>'; return false; } elseif (filter_var($firstname, FILTER_VALIDATE_INT) || (filter_var($lastname, FILTER_VALIDATE_INT))) { echo '<p class="error">First name or last name cannot be integers!</p>'; return false; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo '<p class="error">Email address not valid!</p>'; return false; } elseif (strlen($uname) && (strlen($pmd) < '6' )) { echo '<p class="error">Username or password must be minimum 6 characters!</p>'; return false; } else { $query = "INSERT INTO login (id, firstname, lastname, emailaddress, username, password) VALUES('', '$firstname', '$lastname', '$email', '$uname', '$pmd')"; mysql_query($query, $connect); if (mysql_num_rows(mysql_query("SELECT * FROM login WHERE emailaddress = '$email' username = '$uname'"))) { echo '<p class="fail">This email or username is already taken!</p>'; } } } } ?> The warning message I am getting: Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\miniimagehosting\register.php on line 44 i need help trying to get this delete feature to work its not deleting from the database (by the way i took out my database names and passwords at the top of the file) is it possible someone could help me, ive been working on this for like a week and cant figure out the problem. thanks! you can email me at spr_spng@yahoo.com picture 2.png is showing what it looks like Code: [Select] <?php $host="localhost"; // Host name $username="username"; // Mysql username $password="password"; // Mysql password $db_name="database_name"; // Database name $tbl_name="table_name"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql="SELECT * FROM $tbl_name"; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <style> /*table affects look of the whole table look */ table { margin-left: auto; margin-right: auto; border: 1px solid #330000; border-collapse:collapse; width:70%; border-width: 5px 5px 5px 5px; border-spacing: 1px; border-style: outset outset outset outset; border-color: #330000 #330000 #330000 #330000; border-collapse: separate; background-color: #330000; #800517 f535aa #330000 school color #9A0000 school color2 #991B1E school color3 #CCCC99 school color4 #9A0000 } /*th is table header */ th { text-align: left; height: 2.5em; background-color: #330000; color: #FC0; font-size:1.5em; } /*td is table data or the cells below the header*/ td { text-align: left; height:1.0em; font-size:1.0em; vertical-align:bottom; padding:10px; border-width: 5px 5px 5px 5px; padding: 8px 8px 8px 8px; border-style: outset outset outset outset; border-color: #9A0000 #9A0000 #9A0000 #9A0000; background-color: #CCCC99; -moz-border-radius: 0px 0px 0px 0px; } </style> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td><form name="form1" method="post" action=""> <table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"> <tr> <td bgcolor="#FFFFFF"> </td> <td colspan="4" bgcolor="#FFFFFF"><strong>Pick Which Rows you want to delete, Then press delete.</strong> </td> </tr> <tr> <td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td> <td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td> <td align="center" bgcolor="#FFFFFF">delete</td></tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['name']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['lastname']; ?></td> <td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td> <td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td> </tr> <?php } ?> <tr> <td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <? // Check if delete button active, start this // edited if($delete){ for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "DELETE FROM $tbl_name WHERE id='$del_id'"; $result = mysql_query($sql); } // if successful redirect to delete_multiple.php if($result){ echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">"; } } mysql_close(); ?> </table> </form> </td> </tr> </table> HI, according to my knowledge session_destroy() function would destroy all session variables and mysql_close() would close connection with the database. i make a simply logoff.php file and close myssql connection and destroy session. but i still get values from the database and session variables. and doesnt work properly here is the code Code: [Select] <?php session_start(); /* * To change this template, choose Tools | Templates * and open the template in the editor. */ require_once '../database/db_connecting.php'; $dbname="sahansevena";//set database name $con= setConnections();//make connections use implemented methode in db_connectiong.php mysql_select_db($dbname, $con); //update the time and date of the admin table $update_time="update admin set last_logged_date =CURDATE(), last_log_time=CURTIME() where username='$uname'limit 3,4"; //my admin table contain 5 colums they are id, username,password, last_logged_date, last_log_time $link= mysql_query($update_time); // mysql_select_db($dbname, $link); //$con=mysql_connect('localhost', 'root','ijts'); $result="select * from admin where username='a'"; $result=mysql_query($result); mysql_close($con); //here i just check after closing data baseconnection whether i do get reselts but i do, why? echo "after the cnnection was closed"; echo "<html>"; echo "<table border='1' cellspacing='1' cellpadding='2' align='center'>"; echo "<thead>"; echo"<tr>"; echo "<th>"; echo ID; echo"</th>"; echo" <th>";echo Username; echo"</th>"; echo"<th>";echo Password; echo"</th>"; echo"<th>";echo Last_logged_date; echo "</th>"; echo "<th>";echo Last_logged_time; echo "</th>"; echo" </tr>"; echo" </thead>"; echo" <tbody>"; while($row= mysql_fetch_array($result,MYSQL_BOTH)){ echo "<tr>"; echo "<td>"; echo $row[0]; echo "</td>"; echo "<td>"; echo $row[1]; echo "</td>"; echo "<td>"; echo $row[2]; echo "</td>"; echo "<td>"; echo $row[3]; echo "</td>"; echo "<td>"; echo $row[4]; echo "</td>"; echo "</tr>"; } echo" </tbody>"; echo "</table>"; echo "</html>"; session_destroy(); session_commit(); echo "session and database are closed but i still get values".$_SESSION['admin']; ?> It works other then the fact it won't go to another page to see results. <?php // Get the search variable from URL $var = @$_GET['q'] ; $trimmed = trim($var); //trim whitespace from the stored variable // rows to return $limit=10; // check for an empty string and display a message. if ($trimmed == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","username","password"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("database") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "select * from the_table where 1st_field like \"%$trimmed%\" order by 1st_field"; // EDIT HERE and specify your table and field names for the SQL query $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); // If we have no results, offer a google search as an alternative if ($numrows == 0) { echo "<h4>Results</h4>"; echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>"; echo "<p><a href=\"http://www.google.com/search?q=" . $trimmed . "\" target=\"_blank\" title=\"Look up " . $trimmed . " on Google\">Click here</a> to try the search on google</p>"; } // next determine if s has been passed to script, if not use 0 if (empty($s)) { $s=0; } // get results $query .= " limit $s,$limit"; $result = mysql_query($query) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> Hi, I am not sure why but my script is not working. Choose a post is not working http://beta.cwuforum.com/stock/tech.php Code: [Select] <?PHP $idofp = $_REQUEST['bida']; ?> <!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=UTF-8" /> <title>Ryan Weekly</title> <style type="text/css"> body { background-color: #E3E5E2; } </style> </head> <style type="text/css"> <!-- body { font-size:12px; font-family:Verdana, Arial, Helvetica, sans-serif; } div#wrapper { width: 80%; background-color:#FFFFFF; margin-top: 50px; margin-bottom: 50px; margin-left: auto; margin-right: auto; padding: 0px; border: thin solid #000000; } div#header { padding: 15px; margin: 0px; text-align: center; } div#nav { width: 25%; padding: 10px; margin-top: 1px; float: left; border: thin solid #000000; } div#main { margin-left: 30%; margin-top: 1px; padding: 10px; border: thin solid #000000; } div#underhead { padding: 15px; margin: 0px; border-top: thin solid #000000; } { ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background: #6F7D94; color: #FFF; } .content ul, .content ol { padding: 0 15px 15px 40px; /* this padding mirrors the right padding in the headings and paragraph rule above. Padding was placed on the bottom for space between other elements on the lists and on the left to create the indention. These may be adjusted as you wish. */ } /* ~~ The navigation list styles (can be removed if you choose to use a premade flyout menu like Spry) ~~ */ ul.nav { list-style: none; /* this removes the list marker */ border-top: 1px solid #666; /* this creates the top border for the links - all others are placed using a bottom border on the LI */ margin-bottom: 15px; /* this creates the space between the navigation on the content below */ } ul.nav li { border-bottom: 1px solid #666; /* this creates the button separation */ } ul.nav a, ul.nav a:visited { /* grouping these selectors makes sure that your links retain their button look even after being visited */ padding: 5px 5px 5px 15px; display: block; /* this gives the link block properties causing it to fill the whole LI containing it. This causes the entire area to react to a mouse click. */ text-decoration: none; background: #8090AB; color: #000; } ul.nav a:hover, ul.nav a:active, ul.nav a:focus { /* this changes the background and text color for both mouse and keyboard navigators */ background: #6F7D94; color: #FFF; } /* ~~ The footer ~~ */ .footer { padding: 10px 0; background: #6F7D94; position: relative;/* this gives IE6 hasLayout to properly clear */ clear: both; /* this clear property forces the .container to understand where the columns end and contain them */ } /* ~~ miscellaneous float/clear classes ~~ */ .fltrt { /* this class can be used to float an element right in your page. The floated element must precede the element it should be next to on the page. */ float: right; margin-left: 8px; } .fltlft { /* this class can be used to float an element left in your page. The floated element must precede the element it should be next to on the page. */ float: left; margin-right: 8px; } .clearfloat { /* this class can be placed on a <br /> or empty div as the final element following the last floated div (within the #container) if the #footer is removed or taken out of the #container */ clear:both; height:0; font-size: 1px; line-height: 0px; } --> </style> <body> <div align="Left"> <p><img src="indexp.png" width="728" height="90" /></p> </div> <div id="underhead"> <form id="bida2" name="form1" method="post" action="tech.php"> Choose Post: <label for="id"></label> <select name="id" id="bida"> <option value="ad1">Google Chrome Netbook </option> </select> <input type="submit" name="send" id="send" value="View" /> </form> </div> <?php include("menu.php"); ?> <div id="main"> <?PHP if (empty($idofp)) include ("canoncamera1.php"); if ($idofp == ad1) include ("chromenetbook.php"); ?> </div> Ryan Weekly 2009 - 2011 (May 11, 2011 at 6:00PM Is our 3 Year anniversary!) </body> </html> I came up with the following script for displaying an uploaded picture on a webpage but for some reason I can't pinpoint, the picture won't be displayed. I checked my database from php myadmin and sure enough, the picture was successfully uploaded but somehow, the picture won't be displayed. So here is the display script. I named it display_pic.php Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //include the config file require('config.php'); $image = stripslashes($_REQUEST[imname]); $rs = mysql_query("SELECT* FROM images WHERE member_id = '".$_SESSION['id']."' AND image_cartegory = 'main' "); $row = mysql_fetch_assoc($rs); $imagebytes = $row[image]; header("Content-type: image/jpeg"); print $imagebytes; ?> The tag on the html page that's supposed to display the picture reads something like this <img src="display_pic.php" width="140" height="140"> And just in case this might help, I will include the image upload script below, which I think worked just fine because my values were successfully inserted into the database. Code: [Select] <?php //This file inserts the main image into the images table. //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user //Start session session_start(); //Connect to database require ('config.php'); //Check whether the session variable id is present or not. If not, deny access. if(!isset($_SESSION['id']) || (trim($_SESSION['id']) == '')) { header("location: access_denied.php"); exit(); } else{ // Make sure the user actually // selected and uploaded a file if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { // Temporary file name stored on the server $tmpName = $_FILES['image']['tmp_name']; // Read the file $fp = fopen($tmpName, 'r'); $data = fread($fp, filesize($tmpName)); $data = addslashes($data); fclose($fp); // Create the query and insert // into our database. $query = "INSERT INTO images (member_id, image_cartegory, image_date, image) VALUES ('{$_SESSION['id']}', 'main', NOW(), '$data')"; $results = mysql_query($query); // Print results print "Thank you, your file has been uploaded."; } else { print "No image selected/uploaded"; } // Close our MySQL Link mysql_close(); } //End of if statmemnt. ?> So any insights as to why the script fails to display the image? Any help is appreciated. Hi there, I am starting to learn OO PHP programming. After running math.php, it gives an output 'Use only numbers'. Why? I don't understand this. math.php <?php require('MathClass.php'); $c = new MathClass(); echo $c->add(5,10,15,20); ?> MathClass.php <?php class MathClass{ function add(){ $args = func_num_args(); $sum = 0; $i = 0; for ($i ; $i < $args ; $i++){ is_int(func_get_args($i)) ? $sum += func_get_args($i) : die('Use only numbers'); } return $sum; } } ?> i'm just having a little bit of a play around making a browser-based text RPG with PHP and mySQL. But when it comes to creating a system where a player can view their inventory, and for that matter -have- items. i just don't know where to begin. Would i make a seperate database for inventories and have each column in the database be a different inventory slot and then have the value in that field be in reference to an item? like 1 = potion, 2= ether, etc? with a large amount of items and inventory space for each player i don't want to get started down a long road on the wrong path. To reiterate, I'm not asking for the code specifically i'm just asking what way I would go about it. What would be the simplest, least headachey method of such a system? My first real attempt to mess with MySql. Keep getting a syntax error and I am quite confused. Error: Code: [Select] Parse error: syntax error, unexpected '}' in /home/a8152576/public_html/MemberSystem/install1.php on line 68 Here is my php code: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form id="form1" name="form1" method="post" action=""> <h2><center>Fill in the following info properly to install required databases.</center></h2> <p> <label>Host: <input type="text" name="host" id="host" /> </label> </p> <p> <label>Database User: <input type="text" name="dbUser" id="dbUser" /> </label> </p> <p> <label>Database Password: <input type="text" name="dbPass" id="dbPass" /> </label> </p> <p> <label>Desired Admin Username: <input type="text" name="adminName" id="adminName" /> </label> </p> <p> <label>Desired Admin Password: <input type="text" name="adminPass" id="adminPass" /> </label> </p> <p> <label>Email: <input type="text" name="adminEmail" id="adminEmail" /> </label> </p> <p> <input type="submit" name="submitBtn" id="submitBtn" value="Submit" /> </p> </form> <?php if(isset($_POST['submit'])){ $hostName = $_POST['host']; $dbUserName = $_POST['dbUser']; $dbPassword = $_POST['dbPass']; $adminUserName = $_POST['adminName']; $adminPassword = $_POST['adminPass']; $email = $_POST['adminEmail']; $sqlLink = mysql_connect('$hostName','$dbUserName','$dbPassword'); if(!$sqlLink){ die('Could not connect: ' .mysql_error()); mysql_close(); } else { $queryCreate = 'CREATE DATABASE member_db'; echo 'Connected successfully!'; if(mysql_query($queryCreate,$link)){ echo 'Created database!'; mysql_select_db('member_db'); $createAdminTable = "CREATE TABLE " .$adminUserName. " (`secLvl` tinyint(1) default NOT NULL,`rank` tinyint(2) default NOT NULL,`username` varChar(32) NOT NULL UNIQUE,`password` varChar(32) NOT NULL,`email` varChar(32) NOT NULL UNIQUE"; $insertAdminInfoQuery = "UPDATE " .$adminUserName. " SET `secLvl` = '5', `rank` = '10', `username` = '$adminUserName', `password` = '$adminPassword', `email` = '$email' WHERE '$adminUserName' LIMIT 1"; mysql_query($createAdminTable) or die("ERROR: " .mysql_error()); mysql_query($insertAdminInfoQuery) or die("ERROR: " .mysql_error()) } else { echo 'Error: '.mysql_error(); } } } ?> </body> </html> You can even see the error on this web page directly: http://www.ptcptc.info/MemberSystem/install1.php Thanks, Brandon Hello !
How I can make a script of my PHP code to work even if my website is not running
Can I make this with php ?
Server version: 5.1.53-log I have the following queries Code: [Select] SELECT user_id FROM phpbb_profile_fields_data WHERE pf_rsname = "Atroxide" LIMIT 1 SELECT user_id FROM phpbb_profile_fields_data WHERE pf_rsname = "Delia Smith" LIMIT 1 SELECT user_id FROM phpbb_profile_fields_data WHERE pf_rsname = "espinozagabe" LIMIT 1 SELECT user_id FROM phpbb_profile_fields_data WHERE pf_rsname = "Jaunty1" LIMIT 1 SELECT user_id FROM phpbb_profile_fields_data WHERE pf_rsname = "lvoos" LIMIT 1 All 5 of these queries are executed at a different time (in a foreach loop). All 5 except for the one below returned a result. Code: [Select] SELECT user_id FROM phpbb_profile_fields_data WHERE pf_rsname = "Delia Smith" LIMIT 1 I couldn't figure out why it wasn't working so I copy pasted it into PHPMyAdmin and it returned the result I was looking for. What could cause for PHPMyAdmin to work but not the exact same query in a php script to not? It didn't return an error using mysql_error() either. Pretty sure its irreverent but here is the php script. Code: [Select] foreach ($online as $username => $activity) { $query = " SELECT user_id FROM phpbb_profile_fields_data WHERE pf_rsname = \"" . $username . "\" LIMIT 1 "; $result = $db->query($query); } The table is Code: [Select] user_id mediumint(8) UNSIGNED No 0 pf_rsname varchar(255) utf8_bin Yes NULL Hey... I was going through this sample that was given in the class, but got confused at the first point "//change this to include your own database connect script. include "../../dbconnect.php";" and the database connection code is "<?php if ($_POST['submit']) { // connect to your database $connection = pg_connect("port=5432 dbname=rr_ds user=nobody"); if (!$connection) { die("Connection has failed: " . pg_last_error()); }?> " the database connection code is from a previous assignment which i did, but that was for a login page. The current assignment is to connect to the database and have data on it. Hey, sorry I'm a newb so prepare for me to do everything wrong even though I read the FAQ.
I'm trying to use a simple php script to input data to register but I get this error:
"Failed to run query: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" once I fill out the form.
I've seen other people get this error but I seem to have different problems to them and can't figure it out.
My PHP script is just
<?php require("config.inc.php"); //if posted data is not empty if (!empty($_POST)) { if (empty($_POST['username']) || empty($_POST['password'])) { $response["success"] = 0; $response["message"] = "Please Enter Both a Username and Password."; die(json_encode($response)); } $query = " SELECT 1 FROM users WHERE username = :user"; $query_params = array( ':user' => $_POST['username'] ); try { $stmt = $db->prepare($query); $result = $stmt->execute($query_params); } catch (PDOException $ex) { die("Failed to run query: " . $ex->getMessage()); $response["success"] = 0; $response["message"] = "Database Error. Please Try Again!"; die(json_encode($response)); } $row = $stmt->fetch(); if ($row) { die("This username is already in use"); $response["success"] = 0; $response["message"] = "I'm sorry, this username is already in use"; die(json_encode($response)); } $query = "INSERT INTO users ( username, password ) VALUES ( :user, :pass ) "; $query_params = array( ':username' => $_POST['username'], ':password' => $_POST['password'] ); try { $stmt = $db->prepare($query); $result = $stmt->execute($query_params); } catch (PDOException $ex) { die("Failed to run query: " . $ex->getMessage()); $response["success"] = 0; $response["message"] = "Database Error. Please Try Again!"; die(json_encode($response)); } $response["success"] = 1; $response["message"] = "Username Successfully Added!"; echo json_encode($response); } else { ?> <h1>Register</h1> <form action="index.php" method="post"> Username:<br /> <input type="text" name="username" value="" /> <br /><br /> Password:<br /> <input type="password" name="password" value="" /> <br /><br /> <input type="submit" value="Register New User" /> </form> <?php } ?>and the config: <?php $username = "root"; $password = ""; $host = "localhost"; $dbname = "drinkdealz"; $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); } catch(PDOException $ex) { die("Failed to connect to the database: " . $ex->getMessage()); } $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { function undo_magic_quotes_gpc(&$array) { foreach($array as &$value) { if(is_array($value)) { undo_magic_quotes_gpc($value); } else { $value = stripslashes($value); } } } undo_magic_quotes_gpc($_POST); undo_magic_quotes_gpc($_GET); undo_magic_quotes_gpc($_COOKIE); } header('Content-Type: text/html; charset=utf-8'); session_start(); ?>Sorry if I uploaded anything wrong and it's only a localhost so I don't really care about passwords etc (none will be the same when I upload it) So if any of you can even point me in the direction of what to look for that would be brilliant. Cheers, Kieran Hi, Im just in the middle of creating an update script for my mysql database but don't know why it's not working. p.s. I'm a little new to PHP, but know quite a bit, it's probably something really small.. *facepalm* Here's the script: the form (update.php) <? // Connect to the database $link = mysql_connect('###', '###', '###'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('###', $link); $id = $_GET['id']; // Ask the database for the information from the links table $query="SELECT * FROM orders WHERE id='$id'"; $result = mysql_query("SELECT * FROM orders"); $num=mysql_numrows($result); mysql_close(); $i=0; while ($i < $num) { $name=mysql_result($result,$i,"Name"); $location=mysql_result($result,$i,"Location"); $fault=mysql_result($result,$i,"Fault"); ?> <form action="updated.php" method="post"> <input type="hidden" name="ud_id" value="<? echo "$id";?>"> Name: <input type="text" name="ud_name" value="<? echo "$name"?>"><br> Location: <input type="text" name="ud_location" value="<? echo "$location"?>"><br> Fault: <input type="text" name="ud_fault" value="<? echo "$fault"?>"><br> <input type="Submit" value="Update"> </form> <? ++$i; } ?> ------------------------------------------------------ (processor) updated.php <?php // Connect to the database $link = mysql_connect('###', '###', '###'); if (!$link) { die('Could not connect: ' . mysql_error()); } mysql_select_db('###', $link); $query="UPDATE orders SET Name='" . $_POST['ud_name'] . "', Location='" . $_POST['ud_location'] . "', Fault='" . $_POST['ud_fault'] . "' WHERE $id='" . $_POST['ud_id'] . "'"; echo $query; $checkresult = mysql_query($query); if ($checkresult) echo '<p>update query succeeded'; else echo '<p>update query failed'; mysql_close(); ?> ------------------------------------------------------ Every time I want to update, it comes up with: UPDATE orders SET Name='TEST', Location='TEST', fault='jbjh' WHERE ='' update query failed Any help would be appreciated. |