-
Posts
5,450 -
Joined
-
Days Won
175
Everything posted by mac_gyver
-
i'm going to guess that you have a redirect-loop or similar that's requesting the page multiple times. the symptom you are seeing of random numbers other than a 1 causing the query to update is just the last random value being echoed, but in fact the code has ran several times, one of which had a 1 that caused the query to run. you may also have some other code that's always running the same query or have a logic error that's updating that value when it should be resetting it. at this point, you have a page that doesn't do what you expect. it will likely take seeing all the code on the page that reproduces the problem (less any database credentials) in order to help you.
-
unfortunately, the OP is using the PDO library, based on the error and his connection code posted in the last thread on this forum, but isn't actually learning how to use it, and is therefore getting stuck on the basic steps over and over. @Tom10, the task in this thread is similar to your previous thread. you are trying to form and run a query, an insert query in this case, but are not using all the statements correctly. the only way to get all the statements to work together and correctly is to learn what each of the statements do, so that you will know how they are supposed to go together. in the last thread you were not using the correct bind statement that is part of the PDO library of functions. in this thread, you have a mix of code that is/was running a non prepared query using the pdo->query() method, then added a couple of lines of code trying to turn that into a prepared query, but not converting the sql statement to a prepared query, not using the correct pdo bind statement, and still leaving in the previous call to the pdo query() method. the reason i didn't post any fixed code or link to any php.net documentation in your previous thread, is because you are missing the basic understanding of what these statements and lines of code do and the only way you can gain that understanding is if you actually go and research, internalize, and learn this information. once you know how to use the pdo statements to prepare a query, bind input parameters, execute the query, and retrieve any results, you can then use that knowledge to form and run any kind of query.
-
what are the actual $encounter values when you log/echo them right before the if(){} conditional statement and are you sure that's the actual code that's being ran on the server?
-
it sounds like what you are trying to do isn't what session variables are intended for. the session is just a container for server-side variables that persist between page requests. it's called a session because it's intended to only last one browser session. it's actually not normal to extend the session cookie lifetime. perhaps if you state what some of these different values will be used for, someone can tell you the best way of handling each of them.
-
Call to undefined method PDOStatement::bind_param()
mac_gyver replied to Tom10's topic in PHP Coding Help
no one stated there was a problem with your database connection, so i don't know why you posted the above code. the problem is that there is no pdo bind_param() method. to use the PDO database statements correctly, you must read the php.net documentation for what you are doing. just coping things you have have seen someplace, without knowing what they mean and what they do, isn't going to work. -
your prepare() statements are failing, probably because you haven't selected a database, and your code isn't doing anything when a prepare fails. your code keeps running and tries to use the result from the queries that have failed. your if(){} conditional test for the first two prepare() statements needs to do something when there's a failure, such as reporting that there is an error, prevent the rest of the code from running, and during development display all the information there is about the error. the third prepare() statement doesn't even have any logic around it to make sure it is working before trying to call the bind_param() method. the or trigger_error($mysqli->error); statement you have on the end of the $query = "..." string isn't doing anything (a string cannot produce a mysqli error.) perhaps you meant to have that in an else {} clause for the if(){} conditional test around the prepare() statements?
-
you are making this much harder than it needs to be. you should also post in the javascrpt forum section if you are going to be using js/ajax. the reason your session variable isn't working is due to a logic error. there's no code setting or modifying the session variable. see the following sample code for how you could manage the process using php - <?php /* Create a new session to hold the step values */ session_start(); /* Force start on step 0 when page load, via session */ if(!isset($_SESSION['step'])){ $_SESSION['step'] = 0; } // form processing code if($_SERVER['REQUEST_METHOD'] == "POST"){ $errors = array(); // store any errors in this array $data = array_map('trim',$_POST); // get a trimmed copy of the form data /* Check WHICH form processing code to run */ switch($_SESSION['step']){ case 1: // step 1 form processing code // validate the form data //$errors[] = 'empty host name'; // dummy error for demo purposes // if no validation errors, use the form data if(empty($errors)){ // do something with the submitted data from this step } break; // processing code for the remaining steps would go here case 2: break; } // if there are no errors at this point, advance to the next step and do a header() redirect to the exact same url of this page to cause a get request if(empty($errors)){ $_SESSION['step']++; $host = $_SERVER['HTTP_HOST']; $uri = $_SERVER['REQUEST_URI']; header("Location: http://$host$uri"); exit; } // if there are errors, the code will continue and display the html document, where you would // display any errors, redisplay the current step's form, with any previous values } // any get method code would go here to get/produce data that the page needs, // such as if you are editing existing settings, to retrieve them and set the $data array with them // if the $data array doesn't already exist ?> <!DOCTYPE html> <html> <head> <title>CMS Website : Installer</title> <link rel="stylesheet" type="text/css" href="css/styles.css" /> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,700' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <div id="form-box"> <?php // display any errors if(!empty($errors)){ echo "Correct the following errors:<br>"; foreach($errors as $error){ echo "$error<br>"; } } switch($_SESSION['step']){ case 0: echo ' <h3>CMS Installer</h3> <p>You <small>MUST</small> install the website for it to function correctly.</p> <form method="post"> <div align="center"><input type="submit" value="Start Install" style="cursor: pointer;" /></div> </form> '; break; case 1: // note: to display any initial/existing form field data, test if the corresponding field // in the $data array isset() and echo it as needed to populate the form fields // this would be much easier if you dynamically built (and processed) each form by having a definition in an array that you simply step through echo ' <h3>CMS Installer ~ Step 1</h3> <p>Please fill in the form with the appropriate details</p> <form method="post"> <input type="text" name="db-host" placeholder="Database Host" /> <input type="text" name="db-username" placeholder="Database Username" /> <input type="password" name="db-password" placeholder="Database Password" /> <input type="text" name="db" placeholder="Database Name" /> <input type="submit" value="Submit Database" /> </form> '; break; // display code for the remaining steps would go here case 2: break; } ?> </div> </body> </html>
-
Call to undefined method PDOStatement::bind_param()
mac_gyver replied to Tom10's topic in PHP Coding Help
you are using the PDO statements for your database connection. all of the rest of your database statements must also be PDO statements. the bind_parm() statement you are using is a mysqli statement. you cannot mix the different types of database statements. i recommend that you use the php.net documentation as a reference source to avoid confusion like this. -
web servers can handle several 100's of requests per minute. just using the timer/ajax-request method will work for a casual chat system. you would want to make each request/response as brief as possible and make the server side code as efficient as possible, off loading as much formatting/processing onto the client as possible. the client side request, which should be a GET request btw, would include the id of the last message that has been displayed for that user. the server would just query for and retrieve any new messages with id's greater than that id. at a minimum, the message id column in the database table would be indexed. if there's no new messages, the server should return a simple status value to tell the client side code it doesn't need to do anything, perhaps just an empty json encoded array. if there are new messages, just return the raw message data, leave any formatting/display to the client side code. make sure that the database server has query caching turned on as well. when data in the database table hasn't changed, the same database query being made from multiple clients will return data from the cache rather than retrieving it from the database table. you can have 100's of clients all waiting for a new message and they will keep getting the result from the cache that there's no new messages until there actually is one that was stored into the database table, altering it, which causes the cache to be cleared so that it will then cache the new message(s) for the next series of update requests.
- 10 replies
-
some suggestions that will help you - 1) set php's error_reporting to E_ALL and display_errors to ON in the php.ini on your development system to get php to help you by reporting and displaying all the errors it detects. you will save a ton of time. 2) all the database statements must be from the same library of functions. use all mysqli_ statements. the mysql_error() and mysql_insert_id() statements you have now are not working and are probably throwing php errors (see item #1 in this list.) 3) DRY - (Don't Repeat Yourself). you should not repeat code. factor out the common code and only put the code/data that's different in the conditional statement. this will result in less code that you have to type, test, and change. 4) don't store the cart total in a database table. this is derived information and should be calculated when needed. 5) all external data cannot be trusted and can be anything. external values you put into any sql query statement must be handled correctly to prevent sql injection and to prevent sql errors if the data contains sql special characters. edit: 6) the semi-colon ; does not need to be on the end of sql query statements. 7) you can put php variables inside a double-quoted php string without using concatenation. this will result in less typing and typo errors. associative array variables used this way need to be enclosed in - { } inside the string. all of your add to cart processing code should inside the if(isset($_POST['submit'])){ ... } conditional. If the form hasn't been submitted, there's no point in running any of the processing code. once you complete items #1 and #2, you will likely be getting meaningful errors that will point to why the query is not working.
-
the second parameter of session_set_cookie_params() isn't where the session data is saved on the server, it's the path on your site that the session cookie will match - session_save_path() controls where the session data is saved on the server.
-
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