PHP - Problems With Function And Mysql
Hello PHPFreaks.
I have one problem, that I've tried to fix for a day or two now. I need a function, that picks out a random row in a table, and returns one thing. I tried with, getting the max rows in the table, make a random number in the interval 0 to max rows, then select the random number, but it failed. I hope someone can help me out with this one? -Niixie This is my code, and I know it's pretty messy, because i fooled around with it for a day or two, so it's hard to find head or tail in it. Code: [Select] $query0 = sprintf("SELECT * FROM registertest"); $result = mysql_query($query0); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message); } $nums = mysql_num_rows($result); $rand_nums = rand(0,$nums); $query1 = sprintf("SELECT question FROM registertest WHERE id='%i'", $rand_nums); $result1 = mysql_query($query1) or die(mysql_error()); if (!$result1) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message); } $row = mysql_fetch_row($result1); mysql_free_result($result); mysql_free_result($result1); $_SESSION['registerquestion'] = $row; if(strlen($_SESSION['registerquestion'])!=0){return 1;}else{return 0;} Similar TutorialsI am trying to check whether a given value exists in the database or not before inserting/deleting/updating it. So i will be doing it using 4 functions, one is to check if the record exists and other 3 to add, update & delete. Here is a sample code Code: [Select] function check($k) { $chk="select * from tablename where columnname = '$k'"; $res=mysql_query($chk); $count = mysql_num_rows($res); if ($count>0) { return false; } } function add($a) { $sql="insert into tablename values('$a')"; $exec = mysql_query($sql); if($exec) { echo "row added successfully"; } else { echo "could not update table"; } } How do i control the add function on the basis of the output of the check function? Hello Im just new to coding into php and im getting this error? i cant seems to see database into my php ? what wrong need help CREATE TABLE IF NOT EXISTS `payment_details` ( `id` int(11) NOT NULL AUTO_INCREMENT, `idnumber` varchar(30) NOT NULL, `date` varchar(30) NOT NULL, `amount` varchar(30) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;Here my php code i cant seems to understand what wrong i dont get any error from mysql or from my php please i dont know what wrong <label for="filter">Filter</label> <input type="text" name="filter" value="" id="filter" /> <table cellpadding="1" cellspacing="1" id="resultTable"> <thead> <tr> <th style="border-left: 1px solid #C1DAD7"> Date </th> <th>Amount</th> </tr> </thead> <tbody> <?php include('../connect.php'); $id=$_SESSION['SESS_MEMBER_ID']; $result = mysql_query("SELECT * FROM student WHERE id='$id'"); while($row = mysql_fetch_array($result)) { echo '<tr class="record">'; echo '<td style="border-left: 1px solid #C1DAD7"><div align="left">'.$row['date'].'</div></td>'; echo '<td><div align="left">'.$row['amount'].'</div></td>'; echo '</tr>'; } ?> </tbody> </table> It seems the code below doesn't work properly. Even if there isn't a record that has the same username or name, it will say there is on in the database, which prevents them from making an account. Why so? Code: [Select] $check1 = $db->prepare("SELECT username,name FROM servers WHERE username = ? OR name = ? LIMIT 1"); $check1->execute(array($username, $password)); if($check1->rowCount() > 0) { echo "Sorry, there is already an account with this username and/or server name!"; } And here is my other problem, the harder one. It seems my execute wont work properly. The data will NEVER insert in the database, and it just says: "You've successfully created your account!" Here is my code: Code: [Select] $insertQuery = $db->prepare("INSERT INTO servers (id, username, password, name, type, description, ip, votes, beta) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); $insertQuery->execute(array(null, $username, $password, $name, $server_type, $description, $ip, 0, 1)); if($insertQuery->errorInfo() > 0) { echo "Sorry, there was the following error:"; print_r($insertQuery->errorInfo()); } else { echo "Server has been succesfully created!"; } [MAY LOOK SLOPPY. CODED IN NOTEPAD++, BEST VIEWED WITH IT.] Full, whole page code: Code: [Select] <?php include_once("includes/config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><? $title; ?></title> <meta http-equiv="Content-Language" content="English" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <h1><? $title; ?></h1> <h2><? $description; ?></h2> </div> <? include_once("includes/navigation.php"); ?> <div id="content"> <div id="right"> <div id="artlicles"> <?php if(!$_SESSION['user']) { $username = $_POST['username']; $password = $_POST['password']; $name = $_POST['name']; $server_type = $_POST['type']; $description = $_POST['description']; //This check isn't 100% secure. It allows for registration with no server details if(!$username || !$password) { //Ideally HTML and PHP should be as separate as possible. Perhaps consider having a different PHP script that runs the registration echo "Note: Descriptions allow HTML. Any abuse of this will result in an IP and account ban. No warnings!<br><form action='create.php' method='POST'><table><tr><td>Username</td><td><input type='text' name='username'></td></tr><tr><td>Password</td><td><input type='password' name='password'></td></tr>"; echo "<tr><td>Sever Name</td><td><input type='text' name='name' maxlength='35'></td></tr><tr><td>Type of Server</td><td><select name='type'> <option value='Any'>Any</option> <option value='PvP'>PvP</option> <option value='Creative'>Creative</option> <option value='Survival'>Survival</option> <option value='Roleplay'>RolePlay</option> </select></td></tr> <tr><td>Description</td><td><textarea maxlength='1500' rows='18' cols='40'></textarea></td></tr>"; echo "<tr><td>Submit</td><td><input type='submit'></td></tr></table></form>"; } elseif(strlen($password) < 8) { echo "Password needs to be higher than 8 characters!"; } elseif(strlen($username) > 13) { echo "Username can't be greater than 13 characters!"; } else { $check1 = $db->prepare("SELECT username,name FROM servers WHERE username = ? OR name = ? LIMIT 1"); $check1->execute(array($username, $name)); if($check1->rowCount() > 0) { echo "Sorry, there is already an account with this username and/or server name!"; } else { $ip = $_SERVER['REMOTE_ADDR']; $insertQuery = $db->prepare("INSERT INTO servers (id, username, password, name, type, description, ip, votes, beta) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); $insertQuery->execute(array(null, $username, $password, $name, $server_type, $description, $ip, 0, 1)); if($insertQuery->errorInfo() > 0) { echo "Sorry, there was the following error:"; print_r($insertQuery->errorInfo()); } else { echo "Server has been succesfully created!"; } } } } else { echo "You are currently logged in!"; } ?> </div> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <a href="http://www.templatesold.com/" target="_blank">Website Templates</a> by <a href="http://www.free-css-templates.com/" target="_blank">Free CSS Templates</a> - Site Copyright MCTop </div> </div> </body> </html> Hi, I'm not sure if this should be posted in the PHP forum or the mySQL forum as it's a bit of both to be honest. Basically I am generating what I think is a fairly complex SQL statement (although I'm by no means a mySQL master so it might not be that complex) through the use of PHP. The PHP that is generating the statement looks like so: Code: [Select] // Availability $availability = 'SELECT * FROM indivdual_teachers WHERE 1=1'; foreach($_GET as $key=>$value){ if(strpos($key, 'availability_') == 0 and $value=='Available'){ $day = (int)str_replace('availability_', '', $key); $availability .= ' AND teacher_id IN (SELECT candidate_id FROM availability_calendar WHERE (DAY = '.$day.' AND MONTH = '.$month.' AND YEAR = '.$year.' AND availability = "Available")) '; } } // Staff Yype if($_GET['staff_required'] == 'Non Teaching Staff') { $search_str[] = "role !=\"\""; } elseif($_GET['staff_required'] == 'Teaching Staff') { $search_str[] = "role=\"\""; } else { } // Lives in... if(!empty($_GET['location'])) { $location = mysql_real_escape_string($_GET['location']); $search_str[] = "address2 LIKE '%$location%' OR city LIKE '%$location%'"; } elseif(!empty($_GET['region'])) { $region = mysql_real_escape_string($_GET['region']); $search_str[] = "region = '$region'"; } else { // They don't want to search on lives in... so do nothing } // Registered with... if(!empty($_GET['LA'])) { $local_authority = mysql_real_escape_string($_GET['LA']); $search_str[] = "id IN (SELECT teacher_id FROM teacher_LEAs WHERE LEA = '$local_authority')"; } elseif (!empty($_GET['Agency'])) { $agency = mysql_real_escape_string($_GET['Agency']); $search_str[] = "id IN (SELECT teacher_id FROM teacher_agencies WHERE agency = '$agency')"; } else { // They don't want to search on registered with... so do nothing } $total = $_GET["keywords"]; $keyarr = explode(',',$total); // In order to process this array values here is the code foreach($keyarr as $key=>$value) { // becareful to check the value for empty line $value = trim($value); if (!empty($value)) { $search_str[] = "id IN (SELECT teacher_id FROM test_cv_tags WHERE skills = '$value')"; } } // Subject/Specalism if(!empty($_GET['subject'])) { $subject = mysql_real_escape_string($_GET['subject']); $search_str[] = "id IN (SELECT teacher_id FROM teacher_specialisms WHERE specalism = '$subject')"; } if(!empty($_GET['additional_subject'])) { $additional_subject = mysql_real_escape_string($_GET['additional_subject']); $search_str[] = "id IN (SELECT teacher_id FROM teacher_additional_subjects WHERE subject = '$additional_subject')"; } // Ranking if(!empty($_GET['overall'])) { $overall = mysql_real_escape_string($_GET['overall']); $search_str[] = "avg_overall >= $overall "; } else { if(!empty($_GET['behaviour'])) { $behaviour = mysql_real_escape_string($_GET['behaviour']); $search_str[] = "avg_behaviour_management >= $behaviour "; } if(!empty($_GET['ability'])) { $ability = mysql_real_escape_string($_GET['ability']); $search_str[] = "avg_teaching_ability >= $ability "; } if(!empty($_GET['planning'])) { $planning = mysql_real_escape_string($_GET['planning']); $search_str[] = "avg_preperation_planning >= $planning "; } if(!empty($_GET['professional'])) { $professionalism = mysql_real_escape_string($_GET['professional']); $search_str[] = "avg_professionalism >= $professionalism "; } } This is all brought together like so; Code: [Select] if(!empty($search_str)){ $sql = "$availability AND ".join(" AND ", $search_str)." AND public_profile = 'Yes' ORDER BY avg_overall DESC"; echo $sql; } else { $sql = "$availability AND public_profile = 'Yes' ORDER BY avg_overall DESC"; echo $sql; } When I complete my form and echo the completed query it looks something like this; Code: [Select] SELECT * FROM indivdual_teachers WHERE 1=1 AND teacher_id IN (SELECT candidate_id FROM availability_calendar WHERE (DAY = 19 AND MONTH = 04 AND YEAR = 2012 AND availability = "Available")) AND role="" AND region = 'North East' AND id IN (SELECT teacher_id FROM teacher_agencies WHERE agency = 'Education World') AND id IN (SELECT teacher_id FROM test_cv_tags WHERE skills = 'french') [color=red]AND[/color] id IN (SELECT teacher_id FROM test_cv_tags WHERE skills = 'golf') [color=red]AND[/color] id IN (SELECT teacher_id FROM test_cv_tags WHERE skills = 'spanish') AND id IN (SELECT teacher_id FROM teacher_specialisms WHERE specalism = 'Accounting') AND id IN (SELECT teacher_id FROM teacher_additional_subjects WHERE subject = 'Art') AND avg_behaviour_management >= 5 AND avg_teaching_ability >= 5 AND avg_preperation_planning >= 5 AND avg_professionalism >= 5 AND public_profile = 'Yes' ORDER BY avg_overall DESC The problem I have is that the part I have highlighted in red should actually be an OR statement in order for the query to work as intended. I realise why it is an AND statement, simply because it is using this (highlighted in green). I can't simply change the green AND to an OR because that would cause the rest of my query to misfunction; Code: [Select] $sql = "$availability AND ".join(" [color=green]AND[/color] ", $search_str)." AND public_profile = 'Yes' ORDER BY avg_overall DESC"; However I have been unable to resolve the issue. Would someone be kind enough to offer me some advice/guidance here? Many thanks. Hi all, I have a query that runs just fine from the command line in MySQL, but when I try to run the exact same query using PHP to query the same database I get an error. The query is: SELECT Street, City, ZipCode, providers.bWebpage, OpHours.Open, OpHours.Close, lat, lng, ( 3959 * acos( cos( radians('41.757787') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('-88.321416') ) + sin( radians('41.757787') ) * sin( radians( lat ) ) ) ) AS distance FROM Providers, OpHours WHERE providers.bName = OpHours.bName AND OpHours.Close > '17:00:00' HAVING distance < '10' ORDER BY distance LIMIT 0 , 30 Like I stated above, when I run this query from the MySQL command line it returns 12 rows, which is what it should. But when I try executing the same query via PHP I get this error message: Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''17:00:00' HAVING distance < '10' ORDER BY distance LIMIT 0 , 30' at line 1 The PHP code is thus: $connection=mysql_connect ($server, $username, $password); if (!$connection) { echo 'Connection error'; die("Not connected : " . mysql_error()); } $db_selected = mysql_select_db($database, $connection); if (!$db_selected) { echo 'Database selection error' . '\n'; die ("Can\'t use db : " . mysql_error()); } $query = sprintf("SELECT Street, City, ZipCode, providers.bWebpage, OpHours.Open, OpHours.Close, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM Providers, OpHours WHERE providers.bName = OpHours.bName %s HAVING distance < '%s' ORDER BY distance LIMIT 0 , 30", mysql_real_escape_string($center_lat), mysql_real_escape_string($center_lng), mysql_real_escape_string($center_lat), mysql_real_escape_string($hours), mysql_real_escape_string($radius)); $result = mysql_query($query); if (!$result) { die("Invalid query: " . mysql_error()); } I've also checked the MySQL logs and they don't report any errors. I'm running this on a Mac using Snow Leopard. MySQL version is 5.1.37 and the PHP version is 5.2.11. If it makes any difference both of these are from MAMP version 1.8.4. I have a db.php and inside it I filled out all the info needed:
<?php define('DB_HOST', 'example.com'); define('DB_NAME', 'database_name'); define('DB_USERNAME', 'user_name'); define('DB_PASSWORD', '*******'); $odb = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD); ?>My problem is with the DB_HOST, is that my direct URL to the site? for example, google.com or is it like an IP? Hi, I only just worked out (a little slow) that mysql is not redundant and crap =\ Apparently I should be using mysqli.
However I need help I tried following a tutorial online but it failed. This is my login script and it doesn't work
<?php require_once '../inc/conn.php'; session_start(); if ($_POST['username']) { $username = $_POST['username']; $password = $_POST['password']; $requestLogin = mysqli_query( $retreat, "SELECT * FROM login WHERE username='$username' AND password='$password'"); while($row = mysqli_fetch_array($requestLogin)){ $userID = $row['userID']; $_SESSION['userID'] = $userID; $username = $row['username']; $_SESSION['username'] = $username; header('location: /administrator/'); } } ?>And this is the conn.php ( something hidden for safety, however it does connect correctly. <?php $hostname = 'localhost'; $username = ''; $password = ''; $database = ''; $retreat = mysqli_connect($hostname, $username, $password, $database) or die('Connecting to MySQL failed'); ?>The actual <form> is also correct as it's just normal html and worked before I tried converting to mysqli. After this login I have a script which is this that goes in the header of all admin pages. <?php require_once '../inc/conn.php'; session_start(); if (isset($_SESSION['userID'])) { $username = $_SESSION['username']; $getUser = mysqli_query( $retreat, "SELECT user_rights FROM login WHERE username='$username'"); while($row = mysqli_fetch_array($getUser)){ $user_rights = $row['user_rights']; } } else { include_once 'login.php'; exit(); } ?>I am no coding professional by any means but I get the job done. However this mysqli is sort of new ground. I have a post.php that is suposted to run a mysql query, and it used to, but it won't anymore and I don't have the old file. Can someone just look see if there is something i'm missing? <?php //header("Location: ./?p=UCP"); setcookie("Errors", 0, time()-3600); // Connects to your Database mysql_connect("SERVER", "USER", "PASS") or die(mysql_error()); mysql_select_db("DB") or die(mysql_error()); if (isset($_POST['remove'])) { $id=$_POST['ID']; if($_POST['initals'] == "NLW") { if (is_numeric ($id)) { mysql_query("DELETE FROM `users` WHERE `users`.`ID` = $id LIMIT 1"); $error="<span style="; $error .="color:green"; $error .=">"; $error .= "User Removed."; $error .="</span>"; setcookie(Errors, $error, time()+20); } else { $error="<span style="; $error .="color:red"; $error .=">"; $error .= "Please enter a valid ID"; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); } } else { $error="<span style="; $error .="color:red"; $error .=">"; $error .="Initials are not correct"; $error .="<span/>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); } } elseif (isset($_POST['submit'])) { //This makes sure they did not leave any fields blank if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= "You did not complete all of the required fields"; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); } // checks if the username is in use if (!get_magic_quotes_gpc()) { $_POST['username'] = addslashes($_POST['username']); } $usercheck = $_POST['username']; $check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'") or die(mysql_error()); $check2 = mysql_num_rows($check); //if the name exists it gives an error if ($check2 != 0) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= "Sorry, the username is already in use."; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location ./?p=UPC'); } // this makes sure both passwords entered match if ($_POST['pass'] != $_POST['pass2']) { $error="<span style="; $error .="color:red"; $error .=">"; $error .= 'Your passwords did not match.'; $error .="</span>"; setcookie(Errors, $error, time()+20); echo $error; } // here we encrypt the password and add slashes if needed $_POST['pass'] = md5($_POST['pass']); if (!get_magic_quotes_gpc()) { $_POST['pass'] = addslashes($_POST['pass']); $_POST['username'] = addslashes($_POST['username']); $_POST['pass2'] = $_POST['pass2']; } // now we insert it into the database $insert = "INSERT INTO users (username, password, Human-Readable) VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['pass2']."')"; mysql_query("INSERT INTO users (username, password, Human-Readable) VALUES ('".$_POST['username']."', '".$_POST['pass']."', '".$_POST['pass2']."')"); $error="<span style="; $error .="color:green"; $error .=">"; $error .= "<h1>User Registered</h1> <p><h2>Thank you, the user has been registered - he/she may now login</a>.</h2></p>"; $error .="</span>"; setcookie(Errors, $error, time()+20); header('Location: ./?p=UCP'); } else { header('Location: ./?p=UCP'); echo $error; } ?> The remove function works but its the submit. Thanks in advanced I wasn't too sure if this should be in the MySQL help section so please (admin/mods) feel free to move this if you feel it's necessary. I'm attempting to connect to a URL through cURL that is being grabbed from a mysql table. The url within the table is: http://es-us.noticias.yahoo.com/ue-podr%C3%ADa-revisar-veda-crudo-ir%C3%A1n-en-pr%C3%B3ximos-124018543.html" When I plug this into firefox it works. When using it through cURL directly (see below) it works. Code: [Select] $url = "http://es-us.noticias.yahoo.com/ue-podr%C3%ADa-revisar-veda-crudo-ir%C3%A1n-en-pr%C3%B3ximos-124018543.html"; // create a new curl resource $ch = curl_init(); // set URL to download curl_setopt($ch, CURLOPT_URL, $url); // user agent: curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); // remove header? 0 = yes, 1 = no curl_setopt($ch, CURLOPT_HEADER, 0); // should curl return or print the data? true = return, false = print curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // timeout in seconds curl_setopt($ch, CURLOPT_TIMEOUT, 60); // download the given URL, and return output $page = curl_exec($ch); However, when I grab the url from a table within mysql it does not work and no curl error (or any error for that matter) is returned. Code: [Select] $get_url_links = "SELECT * FROM tabe"; $url_link = mysql_query($get_url_links); $row = mysql_fetch_array($url_link); $url = $row['link']."<br />"; I'm suspecting this is some kind of encoding issue. I've tried $url = mysql_real_escape_string($url); --- before entering it into the table $url = mysql_real_escape_string($url); --- before calling cURL mysql_query("set names 'utf8'"); --- before inserting the url into the table I've also set the column table type to 'text'. Suggestions appreciated. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=323935.0 Hi all, I use a MySQL insert query of the following form: Code: [Select] <?php $insert1= mysql_query ("INSERT INTO tablename (H1, H2, H3) VALUES '$V1','$V2','$V3')"); ?> However, I encounter problems when $V1, $V2 or $V3 contain certain symbols, such as quotes ("'). What is the best way to avoid this? Thanks! Hi I am in the process of converting to Object Oriented from Procedural. To cater for this I have built an admin_login function, contained within a class: 'siteFunctions'. However, I am having trouble pointing the admin form to the function correctly. Every time I click 'submit', the form does not process anything. It doesn't even 'think' about it i.e. show the egg timer.... I have built this script heaps of times using the procedural method, so I guess I am somehow doing something wrong with respect to referencing the action attribute of the form (due to my new approach). I am very new to OO so please go easy on me: I know the script isn't particularly advanced. I just want to get used to putting functions into classes, and then calling the code, before I move onto more advanced stuff. I have placed all of the files within the same folder in order to rule out driectory path issues. Here are the three scripts that I think are relevant (login, functionsClass, and the mysql connection script): Login $pageTitle = "Admin Login"; include("admin_header.php"); include_once("sitefunctions.php"); new siteFunctions(); echo '<div class="admin_main_body">'; <form action="<?php echo htmlentities($_SERVER["PHP_SELF"]);?>" method='post'> <input type="text" name="username" id="username" size="20"> <label>Username</label><br /> <input type="password" name="password" id="password" size="20"> <label>Password</label><br /> <input type="submit" name="submit" id="submit" value="submit"> </form> echo '<div>'; include("includes/admin_footer.php"); sitefunctions.php //$page = "admin_index.php"; class siteFunctions { var $message; function admin_login() { echo '<div class="admin_main_body">'; $message = NULL; if (isset($_POST['submit'])) { require_once ("mysql_connect.php"); if (empty($_POST['username'])) { $u = FALSE; $message .= '<p> Please enter your username </p>'; } else { $u = escape_data($_POST['username']); } if (empty($_POST['password'])) { $p = FALSE; $message .= '<p>You forgot to enter your password </p>'; } else { $p = escape_data($_POST['password']); } if ($u && $p) { // If everything's OK. $query = "SELECT * FROM admin WHERE username= ('$u') AND password=('$p')"; $result = @mysqli_query($GLOBALS["___mysqli_ston"], $query); $row = mysqli_fetch_array($result, MYSQLI_BOTH); if ($row) { session_start(); $_SESSION["admin_id"] = $row[0]; //header("$page"); //Redirects user to admin_index.php //header('location: "$page"'); header ("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "admin_index.php"); //echo '$_SESSION["admin_id"]'; } else { $message = '<p> The username and password combination are incorrect.</p>'; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } else { $message .= '<p>Please try again.</p>'; } } if (isset($message)) { echo '<font color="red">', $message, '</font>'; } //$adminLogin = 'admin_login'; } //Closes function } //Closes class Connection Script // This file contains the database access information. This file also establishes a connection to MySQL and selects the database. // Set the database access information as constants. DEFINE ('DB_USER', 'atkinson'); DEFINE ('DB_PASSWORD', 'XYZ111WA'); DEFINE ('DB_HOST', 'localhost'); DEFINE ('DB_NAME', 'practicesite'); if ($dbc = @($GLOBALS["___mysqli_ston"] = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD))) { // Make the connnection. if (!((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . constant('DB_NAME')))) { // If it can't select the database. // Handle the error. my_error_handler (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_errno($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false)), 'Could not select the database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))); // Print a message to the user, include the footer, and kill the script. echo '<p><font color="red">The site is currently experiencing technical difficulties. We apologize for any inconvenience.</font></p>'; include_once ('includes/footer.php'); exit(); } // End of mysql_select_db IF. } else { // If it couldn't connect to MySQL. // Print a message to the user, include the footer, and kill the script. my_error_handler (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_errno($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false)), 'Could not connect to the database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))); echo '<p><font color="red">The site is currently experiencing technical difficulties. We apologize for any inconvenience.</font></p>'; include_once ('includes/footer.php'); exit(); } // End of $dbc IF. // Function for escaping and trimming form data. function escape_data ($data) { global $dbc; if (ini_get('magic_quotes_gpc')) { $data = stripslashes($data); } return mysqli_real_escape_string( $dbc, trim ($data)); } // End of escape_data() function. Any help would be appreciated. Cheers Will Hi guys I am working on adding a third party php members register and login into a clients web site but every time I try the regidter page is shows me this error message. Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'username'@'localhost' (using password: YES) in /home/cpassoc2/public_html/register-exec.php on line 15 Failed to connect to server: Access denied for user 'username'@'localhost' (using password: YES) This is what i have in the config.php page. <?php define('DB_HOST', 'localhost'); define('DB_USER', 'cpassoc2-memark'); define('DB_PASSWORD', '?????????'); password replaced define('DB_DATABASE', 'cpassoc2-me'); ?> I have set up the my SQL within the control panel of the site, So do i need to do any thing else???, what am i missing???. Mark..... Hello, First post here! I am using a script to store small files into a database. I know it is not highly recommended but this is the only solution I can find in this case. All seems fine when inserting but when retrieving all documents are corrupt. I am working with PHP 5 on Windows server. Part script after upload: (the document is uploaded to the server first and this is working fine) Code: [Select] if (!empty($_FILES)) { $folder = "kenya/docs_temp/";//including last / $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = dirname(__FILE__); $targetPath = substr($targetPath,0,strrpos($targetPath, "uploadify")). $folder; $targetFile = str_replace('\\','/',$targetPath) . $_FILES['Filedata']['name']; $fileName = $_FILES['Filedata']['name']; $tmpName = $_FILES['Filedata']['tmp_name']; $fileSize = $_FILES['Filedata']['size']; $fileType = $_FILES['Filedata']['type']; $conn=odbc_connect('xxx','xxx','xxxx'); $content = file_get_contents($tmpName,true); $content = addslashes($content); if(!get_magic_quotes_gpc()){ $fileName = mysql_real_escape_string($fileName); } $file_info = pathinfo($_FILES['Filedata']['name']); $addDoc = "INSERT INTO tblfiles (file_name,file_type,file_size,file_content,file_extension) VALUES ('".addslashes($fileName)."','".$fileType."','".$fileSize."','".$content."','".$file_info['extension']."')"; odbc_exec($conn,$addDoc); } The the script to retrieve and output to the browser: Code: [Select] $conn=odbc_connect('xxxx','xxx','xxxx'); //get the document $getF = "SELECT * FROM tblfiles WHERE userId = '".$_GET['userId']."' AND fileId = '".$_GET['fileId']."'"; $rsF = odbc_exec($conn,$getF); $size = floor(odbc_result($rsF,'file_size')); $type = odbc_result($rsF,'file_type'); $name = odbc_result($rsF,'file_name'); $content = odbc_result($rsF,'file_content'); ob_end_clean(); header("Content-length: ".$size.""); header("Content-type: ".$type.""); header('Content-Disposition: attachment; filename="'.$name.'"'); echo $content; And finally here is the structure for the table: Code: [Select] CREATE TABLE `tblfiles` ( `fileId` int(11) NOT NULL auto_increment, `userId` int(11) NOT NULL, `file_name` varchar(100) NOT NULL, `file_type` varchar(100) default NULL, `file_size` int(11) default NULL, `file_content` mediumblob, `file_extension` varchar(50) NOT NULL, PRIMARY KEY (`fileId`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; many thanks for any assistance. I hope I'm not being a vampire here sucking the life out of you guys, but I can't find any resources in google that explains how to properly use this function in a mysql array. All it does is add a url for any urls added in plaintext. Code: --- <?php function hyperlink ($string) { $string = preg_replace('#(^|\s)([a-z]+://([^\s\w/]?[\w/])*)#is', '\\1<a href="\\2" target="_blank">\\2</a>', $string); $string = preg_replace('#(^|\s)((www|ftp)\.([^\s\w/]?[\w/])*)#is', '\\1<a href="http://\\2" target="_blank">\\2</a>', $string); $string = preg_replace('#(^|\s)(([a-z0-9._%+-]+)@(([.-]?[a-z0-9])*))#is', '\\1<a href="mailto:\\2">\\2</a>', $string); return $string; } // mysql connection $result = mysql_query("SELECT * FROM top_web_articles ORDER BY ID DESC"); echo "<table border='0'>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td class='newstitle' align='left' valign='top' bgcolor='#D6D6D6'>".$row['Category']."</td></tr>"; echo "<td class='newstitle' align='left' valign='top' bgcolor='#D6D6D6'>". $row['ArticleName'] ."</td></tr>"; echo "<td class='newstitle' align='left' valign='top' bgcolor='#D6D6D6'>"hyperlink(. $row['ArticleDescription'] .);"</td></tr>"; echo "<tr><td class='newstitle' align='left' valign='top' bgcolor='#D6D6D6'><a href='". $row['URL'] . "' target='_blank'><img src='http://www.thenewsguys.ca/images/read entire article.png' alt='' width='130' height='11' border='0' /></a></td>"; echo "</tr>"; echo "<td align='left' valign='top'> </td>"; } echo "</table>"; mysql_close($con); ?> --- Error: "Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/doofyd5/public_html/trevor/playground/displayarticles.php on line 146" (Clearly an error where I'm abusing the heck out of the bolded line. Any ideas on how to properly code this? I had another thread about a problem I was having where it's not loading from the DB right aways. My solution is to make an update function and then have the id's calling it on the page. So the thing I am wondering is how to make a working update function. I have this so far: <?php include blah.... $uid = $_SESSION["user"][0]; $avatarid = $_SESSION["user"][12]; function update($str) { global $db_id; $query="select ".$str." from users where id=".$uid; $result=mysql_query($query, $db_id); $row=mysql_fetch_row($result); return $row[0]; } ?> and then it's being called on the profile page with <?php echo update($avatarid); ?>. I want the update() function to select avatar from users where id = userid and then return the value fresh so it's getting it new from the database every time they refresh the page. Then there won't be a problem with updating old avatar stuff. Currently gives me the error: Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/root/public_html/func.php on line 69 So what am I doing wrong here? thanks for anyone who can help So I have a basic search form that goes through and does a mySQL like '%$sanitizedInput%' to column in the table. The problem I have is that if I have two rows, one with a value "green" and the second "blue", and I do a search for "green", it shows the green result, if I do a search for "blue", it shows the blue result, but if i do a search for "green blue" it returns no results. Any ideas on how to fix this? I have created a function to connect to a required database with a username and password. I have called this db_openConnection() Now for each function that requires a select from a database is it ok just to call the db_OpenConnection() first within the function or should i be keeping open a db connection (using persist, i think) rather than keep creating a connection. I know that the connection ends when you have finished a query any how. Not sure if this is the correct forum or if it should be mysql forum Hi, Doing a Query SELECT * FROM table WHERE field BETWEEN low_number AND high_number If i have three rows with three numbers: IE: 27, 50, 80. and i run the query above, it returns a result of: 27 and 50. How can i get it to return a result of: 27,50, and 80.?? WHY: age range search: i want to return an age range of people = and between the age of say: 20 and 70 but i want to include the 20 and 70. How can i do this? |