-
Posts
5,514 -
Joined
-
Days Won
185
Everything posted by mac_gyver
-
each guest visitor should have a unique id generated for it and used in place of the user_id. if the guest logs in, just replace the unique id with the actual user_id.
-
checking array of data against a database
mac_gyver replied to imperialized's topic in PHP Coding Help
i recommend that you start over and study the code i posted. the code you have has all kinds of variables mixed up and is nothing like what i posted. -
Set variable based on another variable - CASE?
mac_gyver replied to simonp's topic in PHP Coding Help
because you are only mapping one value to another in a set of data, which is doing the same processing for each different value, just use a mapping/lookup array substitution - $map[1] = 'a'; $map[2] = 'b'; $map[3] = 'c'; $var2 = isset($map[$var1]) ? $map[$var1] : 'value not found'; conditional logic statements testing a value are for when you are doing different processing based on a value, such as creating/editing/deleting data... -
checking array of data against a database
mac_gyver replied to imperialized's topic in PHP Coding Help
some sample code (untested) - $this->blogTags = array_filter(array_map('trim',explode(',', $blogTags)),'strlen'); // explode, trim, and remove empty strings // insert any new tags $holders = array_fill(0,count($this->blogTags),'?'); $query = "INSERT IGNORE INTO blogTags (tag) VALUES (".implode('),(',$holders).")"; $stmt = $this->db_connect->prepare($query); $parm = 1; foreach($this->blogTags as $tag){ $stmt->bindValue($parm++, $tag, PDO::PARAM_STR); } $stmt->execute(); // retrieve ids $query = "SELECT id FROM blogTags WHERE tag IN (".implode(',',$holders).")"; $stmt = $this->db_connect->prepare($query); $parm = 1; foreach($this->blogTags as $tag){ $stmt->bindValue($parm++, $tag, PDO::PARAM_STR); } $stmt->execute(); $this->blogTagIds = $stmt->fetchAll(PDO::FETCH_COLUMN); // fetch just the ids as an array -
checking array of data against a database
mac_gyver replied to imperialized's topic in PHP Coding Help
you don't need to select data first, before storing unique values. in fact, there is a race condition with concurrent access where you could have two (or more) instances of your script trying to insert the same tag, and the one(s) who run the insert query last will generate an error because the value was already inserted by the insert query that ran first. your tag column should be defined as a unique index. then, you should just form and run one multi-value INSERT query with the IGNORE keyword in it. then, just run one select query using a WHERE tag IN (....) term to retrieve all the ids at once. -
you would apply urlencode() to each value being put into $searchType as it is being built, not after the fact.
-
i would temporarily modify the 'collation' of the character set so that it will naturally sort. note: this will only work with the lower ascii character set as it uses the high/extended ascii characters to make the 'magic' work - <?php $d[] = "abcd fgh"; $d[] = "abcd0"; $d[] = "abcd1"; $d[] = "abcd2"; $d[] = "abcd3"; $d[] = "abcd10"; $d[] = "abcd11"; $d[] = "abcd22"; $d[] = "abcdefgh"; $d[] = "abcd'fgh"; $d[] = "abcd-fgh"; // call back function to modify the 'collation' of the characters function _collate($str){ $arr = str_split($str); foreach($arr as $key=>$char){ if($char == ' '){ $arr[$key] = chr(0); // space -> null } else { if(!ctype_alnum($char)){ $arr[$key] = chr(ord($char) + 128); // convert to high/extended ascii character } } } return implode($arr); } // call back function to restore the 'collation' of the characters function _decollate($str){ $arr = str_split($str); foreach($arr as $key=>$char){ if($char == chr(0)){ $arr[$key] = " "; // null -> space } else { if(ord($char) >= 128){ $arr[$key] = chr(ord($char) - 128); // convert from high/extended ascii character } } } return implode($arr); } // source and result should look like this - echo 'Source:<pre>',print_r($d,true),'</pre>'; shuffle($d); // make data random, for testing $d = array_map('_collate',$d); // modify the 'collation' so it will natural case sort as expected natcasesort($d); $d = array_map('_decollate',$d); // restore the 'collation' echo 'Result:<pre>',print_r($d,true),'</pre>'; you can also use this method in a usort call back function by altering the 'collation' of the two input values and using strnatcasecmp() to perform the comparison on the two altered values to give the return value from the call back function.
-
ONLY the data being put into the URL is urlencoded(). just value after the = would be urlencoded()
-
the serialized data contains several characters that have significance in a url and in html as delimiters/syntax and must be urlencoded() so that they can exist as part of the value in the url. php will url decode the $_GET values for you.
-
each call/reference to - $db->connected() is creating a new database connection, which doesn't know anything about anything from any previous call. any transaction you start is only available on the database connection where it was started. you need to make one database connection, in the constructor in your conn class.
-
You need to show us how you are including the files. I suspect you are using a URL ( http://your_domain.com/some_path/some_file ), rather than a file system path ( file_system_path/some_file ), and the included code is running in a completely separate instance of the web server, which not only takes several 100 times longer than than using the file system to include the file, but it doesn't have access to the $_SESSION variables that are present in the main file.
-
Header already sent error message on LIVE server
mac_gyver replied to thara's topic in PHP Coding Help
browsing to the included files isn't relevant. in fact, the included files should be stored in a location on the server that cannot be reached via a HTTP request, especially now that you have posted links to them and the major search engines have indexed them. the reason your code functioned (i hesitate to use the word 'worked') on your development system is because php thought it would be funny to hide some basic code and page layout problems and allow poorly written code to function. your development system has the output_buffering setting turned on in the php.ini. i recommend that you turn it off so that code you get to work on your development system won't break just because you moved it to another server. once you make this change, you will be able to fix your code on your development system and it won't have this problem when moving it to your live server. a properly laid out web page must send any http headers before sending anything else to the browser. ALL the html tags, starting with the <!DOCTYPE tag is output that goes to the browser. Any header() statement in your php code must come before even the <!DOCTYPE tag. the solution to this problem is to reorganize your code so that the php control logic that determines what to do on the page, such as redirecting if the user isn't logged in or doesn't have permission to access the page, comes first. the html document your page builds and outputs shouldn't even be started until after the point where you have determined that the current visitor can even access the page. -
you should be storing your dates/datetimes as a mysql DATE or DATETIME data type (unix timestamps are an abomination leftover from the 1970's). if the incoming data isn't already formatted correctly, you can either format it in your php code or use the mysql STR_TO_DATE() function in a query when you store/insert it. what is an example of the incoming $_POST['date'] value?
-
two different people have asked you to tell us what sort of error/symptom or incorrect result you are getting that leads you to believe this isn't working. how do you know it is not working? we are not standing right next to you and can only see the information that you put in your posts
-
you have asked this before - http://forums.phpfreaks.com/topic/295157-code-compare/#entry1507847 please stick to that existing thread and you need to answer the questions asked in order to provide us with information upon which to help you.
-
Problems with Dreamweaver produced Connections code
mac_gyver replied to IanMc's topic in PHP Coding Help
it's possible that the posted code isn't even where the error is coming from. you need to determine for yourself where in your code the error is occurring at. for debugging purposes, add the following two lines of code, immediately after the line with the first opening <?php tag in your main file being requested - ini_set("display_errors", "1"); // display errors error_reporting(-1); // report all errors also, remove the @ error suppressor on the session_start() statement. if you are getting any errors on the session_start() you will want to know so that you can find an fix them, rather than to hide them. -
for your multiple attribute to be able to send the multiple selections, the name needs to be an array - name ='selectDivision[]'
-
Having trouble grouping a PHP list in dropdown menu
mac_gyver replied to vbcoach's topic in PHP Coding Help
your sql query would order the rows in the result set by active first, followed by non-active - -
sorry, but we cannot help you based on that statement. several different things were mentioned or suggested and your exact code determines what the computer tried to do. without knowing what your code is and what incorrect result, error, or symptom you got from that code, we cannot help. several of the things you have shown in your code (this and previous threads) are invalid and would be throwing php errors. do you have php's error_reporting set to E_ALL and display_errors set ON in the php.ini on your development system so that php would help you by displaying all the errors it detects? you will save a ton of time. putting these setting into your code won't do anything for php syntax errors in your main file, as the code never runs to modify the error_reporting/display_errors settings. also, by having your development system set up with these settings, you don't need to remember to turn the settings on for development and turn them off if the code is ever moved to a live server because the setting will be tied to the server and not your code files. next, your code itself does not have any error checking logic in it to detect when statements fail. most of the database statements can fail due to an error of some kind and you should be checking at each step if they failed or not so that you don't throw follow-on errors in later statements when an earlier statement failed. for example, if the ->prepare() statement failed (due to a syntax error in the sql statement), there's no point in trying to bind input parameters or to execute the query. you can either add a conditional statement around each database statement that can fail or you can turn on exceptions for the mysqli statements (see the mysqli_report() statement) and either catch the exceptions yourself (which you would want to do for a real application) or let the uncaught exceptions be caught by php and stop execution and display the information about the error. some critique of your code in this thread (some of these have already been found and fixed by you or pointed out by others) - post #1 - $res->num_rows; just having this on a line by itself doesn't accomplish anything. the ->num_rows property returns a value. you must either assign that value to a variable or use the value in a conditional statement (or pass it as a value to another function.) if($stmt) { this tests if $stmt is a true value. $stmt is the result of the ->prepare() statement. it will be a true value as long as the prepare() didn't fail. post #3 - AND status = ? as a condition in the WHERE clause in the sql query statement. this would be okay if you are trying to find records that have a specific status value, i.e. all the user's that have status = 0, but for what you have stated you are trying to do, authenticate/log in a user, you would not have this as a condition in the WHERE clause, but instead retrieve this value and display a message to the person trying to log in. $status = $res->fetch_assoc(); this fetches the row that the query might have matched, as an associative array. this should be inside the conditional block of code that has tested if the query did match at least one row, since $status will be a false value, not an array, if there was no row to fetch. you still have a $res->num_rows; statement on a line by itself, which doesn't do anything. if($status = "0") { this actually assigns the "0" string to $status, then tests the result of that. one = is an assignment operator. two == are needed for a comparison operator. and as has already been mentioned, $status = $res->fetch_assoc(); will result in $status being an associative array. $status['status'] would actually hold the value from the status column in the database table. it would perhaps be easier to keep the code straight if you use a variable named $row - $row = $res->fetch_assoc();, then use $row['status'] to reference the status column value. finally, php has password hash functions - password_hash()/password_verify(), that produces a random salt for each hashed password, making it little harder for anyone getting a hold of your data to come up with the the original passwords, since they must brute force break each one separately. if you switch to using these functions, you would use password_hash() during registration. to authenticate the visitor, you would retrieve the hashed value from the database table and use password_verify() to test if the entered password corresponds to the hashed password. as always, there are basic examples for all the php functions in the php.net documentation.
-
something tells me that the rows between these two tables (using table names like table1, table2 doesn't provide useful context) are not related to each other using any sort of foreign key, but are two different types of data (that perhaps should all be in one table) that the OP wants to retrieve with the data for each username (which should actually be a userid) together in the result set. if so, you need to use a UNION query.
-
if you are asking about visitors to a site being able to see the raw contents of a .php file, they cannot, since browsing to the file will only show any output from that file. it would require that you have code that's echoing the variables/defined constants holding the database credentials or that your site provided a way for someone to display/download the raw contents of a file on your site, such as by not validating the path and filename being supplied (all external data cannot be trusted and must be validated before use) to a download script or a page controller/template engine that reads the contents of a file and then outputs the content on a page... in the rare event that php on a server ever gets broken and outputs the raw content of .php files or you are using php's short open tags and they get turned off (full opening php tags cannot get turned off), the best place to put ALL included/required files is in a folder that's outside of/below/closer to the disk root folder from your htdocs folder so that they cannot possibly be browsed to. or that your site allows a .php code file to be uploaded onto the server and then browsed to (uploaded files should be placed into a folder that cannot be browsed to) or allows php code to be saved as content that's eval()'ed (using eval() should be avoided unless you know exactly what content is being supplied to it) on the server or allows an external file to be included (the settings that allow this should be turned off) and ran on your server, which would allow someone to run their own php code on your server, which would allow them to take over your site and have access to all of the files anyways.
-
large bulk insertion in mysql problem
mac_gyver replied to farazch's topic in PHP Installation and Configuration
it's likely that you are getting a query error at the 137th line in the csv file, either due to an un-escaped value in the data, a duplicate key error, an empty numerical data value, an incorrectly formatted line in the data, or ... does your code have any sort of error checking logic in it to detect query errors? have you looked at the 137th line of data to see if there's something about it that's different and unexpected? edit: here's a post listing methods for inserting bulk data - http://forums.phpfreaks.com/topic/294621-importing-legacy-data-into-mysql/?do=findComment&comment=1505730 -
Can't download exe file from server to clent's browser
mac_gyver replied to Absolvium's topic in PHP Coding Help
if you tried code that was had header() statements in it and it didn't download the file, you would need to troubleshoot what is causing the problem. the most likely reasons are - 1) outputting something to the browser prior to the header() statements (there would be php detected errors. do you have php's error_reporting/display_errors set to show all php errors?) 2) not using the correct headers (you would need to post what you tried for anyone here to be able to help with it.) -
your code has the closing ) for the isset(...) statement in the wrong place (at the end of the line), producing a php syntax error (Parse error: syntax error, unexpected '&&' (T_BOOLEAN_AND), expecting ',' or ')' in your_file on line 3). the closing ) for the isset() belongs after the $_SESSION[ 'logged_in' ] parameter - isset( $_SESSION[ 'logged_in' ] ) && .... you need to have php's error_reporting set to E_ALL and display_errors set to ON in the php.ini on your development system to get php to help you find these kind of errors. putting these settings into your code won't help with syntax errors in your main file since your code never runs when there is a syntax error and lines trying to change the settings aren't executed. @sford999, while your posted code is syntactically correct, by removing the isset() statement, it will throw php errors when the page is visited when not logged in. also, by just posting 'fixed' code, without any statement of what was wrong with the original code, the OP doesn't learn anything.
-
Having trouble grouping a PHP list in dropdown menu
mac_gyver replied to vbcoach's topic in PHP Coding Help
assuming you always want the Active Leagues optgroup, even if it is empty, and you only want the Non Active leagues one when there are non active records - echo "<select name='whatever you are using'>"; echo "<optgroup label='--- Active Leagues ---'>"; // start with the active optgroup, even if it is empty $last_val = 1; // detect when this changes from active/1 to non active while ($lrow = mssqlfetchassoc($lres)) { // detect a change in regactive from the initial active/1 value if($last_val != $lrow['regactive']) { // value changed, to a zero, since there are only two possible values // close the previous section (even if empty) and start the next section echo "</optgroup>"; echo "<optgroup label='--- Non Active Leagues ---'>"; $last_val = $lrow['regactive']; // remember the new value so that this code only runs once } // output the data within each optgroup echo "<option value={$lrow['l_id']} ", ($l == $lrow['l_id'] ? "selected" : '') , ">{$lrow['night']} {$lrow['type']} {$lrow['size']}s {$lrow['division']}</option>"; } echo "</optgroup>"; // close the last optgroup echo "</select>";