Psycho
Moderators-
Posts
12,157 -
Joined
-
Last visited
-
Days Won
129
Everything posted by Psycho
-
Some notes: The function randColor() is used to create a random color. As Barand explained, when defining colors in an HTML page, they are composed of RGB (Red Green Blue) values, with each component having a value from 0 to 255. FYI: The same RGB process is used in many different contexts to define color. The function defines three variables for those three components with a random value from 0 to 255 using the rand() function. The function then takes those three values and composes them into a string format which can be used in the HTML output. A variable ($tdata) is defined to store the output for the table (i.e. 'tdata' is the table data). There are two loops that use a for() loop. The for loops 1) set an arbitrary variable ($i or $j) to 0, 2) Create a condition to continue the loop as long as the variable is less than a certain value, and 3) increment the variable on each iteration of the loop. for ($i=0; $i<10; $i++) { The first iteration of this loop will set $i equal to 0. The loop will continue as long as the condition of $i being less than 10 is true. $i will be incremented by 1 on each iteration of the loop. Therefore the loop will run 10 times. The outer loop is for the rows of the table and the inner loop is for the columns in the rows (there will be 10 rows). The outer loop adds an opening row tag to the variable to store the output. The inner loop creates the individual cells for the row (there will be 20 cells/columns in each row). First, it calls the function described above to get a new random color for each cell. That color is used in creating the content for the cell that is also stored in the output variable. After each completion of the inner loop a closing row tag is added to the output at the end of the outer loop. Finally, after all the PHP processing is complete, the variable $tdata holds the entirety of the output that was produced. After the PHP code comes the actual HTML output that will be sent to the user. The majority of this is simply a hard coded HTML page. But, the variable with the dynamic content created above is then inserted into the HTML table element. The result of all of this is that on every call to this page an HTML table will be displayed. It will have 10 rows and 20 columns. Each cell in that table will display a random color.
-
Help to get Json data to a comma delimited file
Psycho replied to techboy992's topic in PHP Coding Help
Updated solution from Barand // create array from json data $arr = json_decode(file_get_contents('result.txt'),1); // remove empty records $arr = array_filter($arr); // open output file $fp = fopen('result.csv','w'); foreach ($arr as $record) { // trim the values $rec = array_map('trim', $record); // skip records that only contain " " if($rec[0]==' ') { continue; } // remove non-numeric characters from amount $rec[2] = preg_replace("#[^\d]#", "", $rec[2]); // replace character code with apostrophe $rec[3] = str_replace(''', "'", $rec[3]); // save in output file in csv format fputcsv($fp, $rec); } // close output file fclose($fp); -
Is a single JSON MySQL retrieval faster than individual rows?
Psycho replied to DeX's topic in MySQL Help
Also, all the fields used to JOIN the tables should be indexed. Pretty much anything with "id" int he field name in your case. I was trying to rewrite the query, but without knowing the schema on all the tables it was getting confusing. I *think* your DB design is flawed. The "match_quote_product" appears to be the table to list out the products included in a quote. So, why is there a field for purchase_order_id? Are there different purchase orders for different items int he same quote? There should be a general "purchase_order" table that contains the header data (e.g. date, customer, PO, etc.) Then the details table should include all the items in the quote that reference back to the main record. There also seem to be some circular references that could be a performance issue as well. But, here is my attempt at rewriting the query. But, it may not work. I wouodl have to really understand all the relationships to be sure which would take more time than I am willing to invest. And even then, I would probably have to make changes to the schema as well. SELECT mqp.product_id mqp.price_per_k, mqp.board_feet, mqp.location, mqp.power, mqp.locking_handle_side, mqp.unit_price, mqp.total_price_calculation_id, mqp.quantity, width, length, height, colours.name, total_price FROM match_quote_product mqp JOIN building_products bp ON mqp.product_id = bp.id JOIN match_quote_colour mqc ON mqp.colour_type_id = mqc.colour_type_id AND mqp.quote_id = mqc.quote_id JOIN colours c ON mqc.colour_id = c.id WHERE match_quote_product.quote_id = 50000 AND building_products.purchase_order_id = 5 ORDER BY purchase_order_order ASC -
Is a single JSON MySQL retrieval faster than individual rows?
Psycho replied to DeX's topic in MySQL Help
To add some context to why requinix is asking for this information: There are things that can/should be done to configure a database schema and/or queries to be efficient. But HOW you accomplish that directly depends on how the data is to be used. With respect to the database schema, you will typically want to index any fields that are used for JOINing tables, used in frequent filter conditions, or used in similar contexts. Also, in the actual queries it is possible to write two different queries to return the same results where one is exponentially faster than the other. It is impossible to explain all the ins and outs of how to work with a database efficiently in a forum post. There are whole books written on the subject. So, we need to see the actual details of your DB schema and queries to provide specific advice. -
That can't work. If it looks like it is working - it isn't. This is similar to the earlier problem about the href parameter. You need to understand that computer programs require explicit instructions. Humans are very good at deciphering things that may not be in context, but computers are not. When you define a string such as this: $content = "test"; The computer sees that you want to define a variable. Then it sees the first double quote which tells it that the following content should be assigned to the variable. When it sees the next double quote it takes that as the end of the content to be assigned. You can also use single quotes to define a string (but there are some different rules on how the content is handled). In your code above you start with a double quote. But then, you have a double quote IN THE CONTENT at the end of the src attribute. So, that is the end of the content that would be assigned to the variable. If you start a string with a double quote, use single quotes inside the string or escape any double quotes in the string. Either of these would work $content .= "<td> <a href='$varcomplete'><img src='wp-content/custom/imageicon.png' alt='imageicon' border='0'></a> </td>"; $content .= "<td> <a href=\"$varcomplete\"><img src=\"wp-content/custom/imageicon.png\" alt=\"imageicon\" border=\"0\"></a> </td>";
-
Parameter values (like the href parameter for an anchor tag) should be within quotes so the browser knows where the value starts and ends. If the value is not within quotes it assumes that the first space is the end of the value $content .= "<td> <a href='$varcomplete'>test</a> </td>";
-
As mac_gyver states you have no error handling. You may have other problems, but the only thing I can "see" wrong in your code is the field name "INT". That is a reserved word in MySQL, so you can use it normally as a field name like that. You can either change the field name or you need to enclose the filed name in backticks to tell the MySQL engine that you are referring to the field name and not using the INT command. $query = "INSERT INTO vehicles (VehID, Color1, Color2, PosX, PosY, PosZ, VW, `INT`) VALUES ($vehicleid, $color1, $color2, $posX, $posY, $posZ, $vw, $int)";
-
I would also add that it would be a better idea to handle the timestamps using MySQL than in the PHP code. Also, I think it makes more sense to make the timestamd represent the last activity of the user instead of some arbitrary time in the future. It give you a lot more flexibility - e.g. select the users active within the last 5 minutes or 10 minutes or whatever. Don't use "SELECT *" when you don't really need all the columns. There are performance and security reasons why it is not a best practice. Plus, never run queries within loops - it is a huge resource hog. Learn to do proper JOINs as Jacques1 suggest. Your current loop is running a query for every record in the prior result set, but it pulling the data for the current logged in user - not the user in each record of the result set.
-
@ginerjm, the OP will not have an image for every possible number value. E.g. there will be no "525.jpg" for the number 525. So, the correct process is to iterate over each character in the numeric string. @Jacques1, you are correct. That approach removes the necessity for splitting the string into an actual array. It's never seemed logical to me to reference characters in a string as if it was an array, so that did not come to mind when providing a solution.
-
Um, no. You are incorrect. The "working example" on that page is PHP code that defines an hard-coded array for testing purposes instead of getting the values from a DB. The author even includes the DB logic commented out showing that is how it would really be done. Plus, the way an array is defined looks different than when you output an array using print_r(). The print_r() function is really more of a debugging tool to output an array showing the structure and the values. Expecting that to look exactly like the definition of the array is foolish. The only difference between the hard-coded array in that example and the array built from the code I provided is that the array in that example code has numerically based indexes (i.e. 0, 1, 2) rather than named indexes as will be present from a DB query. I don't know if the values of the indexes will matter or not. But, if they do need to be numerical indexes, then convert the array to remove the named indexes and replace with numerical ones. I would show you how to do that, but apparently you know what you are doing, and don't need any assistance from us. EDIT: And just to be 100% clear. The "JSON Array" code that you are pointing to is not JSON. It is simply the definition of a PHP array. It would still need to be converted to JSON (if that's really what you need).
-
1. Create/download 10 different image files for each digit. 2. Create a function to take a numeric string value and return the HTML with an image for each digit The function could go something like this: function convertToImage($numberStr) { //Check that input only has numeric characters if(!ctype_digit()) { return false; } //Split string into an array of each character $numbersAry = str_split($numberStr); //Loop through each character and create HTML for image $output = ""; foreach($numbersAry as $number) { $output .= "<img src='1.jpg' alt='1'>"; } //Return results return $output; }
-
You can't "echo" an array (it will just output the word Array as you have seen. You either need to iterate through the array elements and echo the values or you can use print_r() to output the whole array. Also, do the string concatenation in the query instead of the php logic. Try this <?php $mysqli = mysqli_connect("localhost", "root", "", "plods"); $sql_locations = "SELECT CONCAT(address1, ', ', address2) as address, Longitude, Latitude FROM southdowns"; $rs_locations = mysqli_query($mysqli, $sql_locations); while( $rs_location = $rs_locations->fetch_assoc() ) { $markers[] = $rs_location; } echo "<pre>".print_r($markers, 1)."</pre>"; ?>
-
I really don't understand what you are trying to do, nor what your problem is. What IS the code doing now and what do you WANT it to do differently? EDIT: What is the "numberoflines" variable supposed to do? Is it supposed to make the "tree" wider, taller, or what?
-
Of course you can. Create an object with a different property for each 'config' name. (EDIT: Note that it does not have to be the same object used to get the data. Instead create a 'standard' dynamic class in which to populate the data and return to the caller) Not tested, but the logic should be sound class Config { private $dbObj; public function __construct($db) { //Set db object $this->dbObj = $db; //Call get method and return result return $this->get(); } public function get() { //Run query to get data $query = 'SELECT config, value FROM config'; $select = $this->dbObj->query($query); //Create object and populate with query results $configObj = new stdClass(); while ($row = $select->fetch(PDO::FETCH_OBJ)) { $configObj->$row->config = $row->value; } //Return object return $configObj; } } $config = new Config($db); echo $config->test; //Where 'test' is the name of any 'config' field from the DB results
-
Yes, I changed some names half way through. As I said - not tested. Add some debugging to validate what IS returned from the query. Updated code: <?php //Create an run the query to get unread message count $queryStr = "SELECT COUNT(*) as unreadCount FROM `inbox` WHERE `to` = :username AND `read` = 0"; $inboxQry = $db->prepare($queryStr); $inboxQry->bindParam(":username", $Username); $inboxQry->execute(); //Get the results & create the output $inbox = $inboxQry->fetch(PDO::FETCH_ASSOC); $inboxCountHtml = ($inbox['unreadCount']) ? "{$inbox['unreadCount']} New" : "0"; //Debug lines echo "Query result: "; var_dump($inboxQry); echo "Fetched Row: "; var_dump($inbox); ?> <div class="FooterText"><a href="Inbox.php">Inbox</a> (<?php echo $inboxCountHtml; ?>)
-
First, a few pointers: 1. Don't use "SELECT *". In this case you only want to know if the user has any unread messages. So, you shouldn't be selecting records and instead just query the count. But, even when you do need data, using * is a bad practice for several reasons which I won't go into right now. 2. As stated above, you just need to do a "SELECT COUNT(*)". That will be much more efficient. 3. Add comments! Even when working on small pieces of code it will save you time in the long run. In regards to your problem. the rowCount() method is supposed to be used on the database result (e.g. "$UsersInbox"). The code above is trying to use it on the the first row from the result set. Additionally, that will be a Boolean FALSE if there were no rows returned. I'm also curious why you are using the hard-coded unread variable since the intent of the query is to get the unread messages. I can't think of a reason why you would want to get only the read messages. Try this (untested) <?php //Create an run the query to get unread message count $queryStr = "SELECT COUNT(*) as unreadCount FROM `inbox` WHERE `to` = :username AND `read` = 0"; $inboxQry = $db->prepare($queryStr); $inboxQry->bindParam(":username", $Username); $inboxQry->execute(); //Get the results $inbox = $inboxQry->fetchObject(); $inbox->unreadCount; //Prepare the output based on results $inboxCountHtml = ($inbox->unreadCount) ? "{$userInbox->unreadCount} New" : "0"; ?> <div class="FooterText"><a href="Inbox.php">Inbox</a> (<?php echo $inboxCountHtml; ?>)
-
Well, I wrote the code based on his initial post which stated But, looking at his last post he magically changed the requirement from dashes to underscores.
-
//Create function to be called using array_map() function updateDataArray($value) { //Check if any letters exist if(preg_match("#[a-z]#i", $value)) { //Contains a letter replace "-" with space return str_replace("-", " ", $value); } //Does not contain letter, return unchanged value return $value; } $original_data = array( 'abcd-efgh', 'xyz-abc', 'alpha-lima-lima', 'bravo-charlie-charlie', '100-500', '1000-5200', '100000-800000' ); //Call the function above as a parameter in the array_map function $modified_data = array_map('updateDataArray', $original_data); echo "<b>Before</b><pre>" . print_r($original_data, true) . "</pre>"; echo "<b>After</b><pre>" . print_r($modified_data, true) . "</pre>"; Before Array ( [0] => abcd-efgh [1] => xyz-abc [2] => alpha-lima-lima [3] => bravo-charlie-charlie [4] => B-B-D [5] => 100-500 [6] => 1000-5200 [7] => 100000-800000 ) After Array ( [0] => abcd efgh [1] => xyz abc [2] => alpha lima lima [3] => bravo charlie charlie [4] => B B D [5] => 100-500 [6] => 1000-5200 [7] => 100000-800000 )
-
Then you don't need DISTINCT. Instead run the query for the records you want and 1) Use a GROUP BY on the item_number with a COUNT() clause in the select list. Something like this SELECT item_number, COUNT(item_number) as item_count FROM queue_test WHERE search_type = '1112' AND date_completed = CURDATE()
-
I already explained "how" from a very general standpoint. If you want details, then you need to provide the specific code where the functionality takes place. The code you provided only creates the HTML form data. To implement #1 requires the server-side code that is called for those two processes. To implement #2 requires the actual code that is generated from the above code that you provided. In either case, someone with sufficient knowledge needs to review the relevant code and then determine (specifically) how to implement. There may be someone here that is generous enough to do that work for free, but it's not me. I was only trying to provide a better explanation of what you were requesting as it seemed there was some confusion.
-
As I understand the current functionality: There is currently a text input field that does a search of any artists which contain the search term. E.g. if you type in "smith" it would return both "Smithereens" and "Aerosmith". There is also a 'rolodex' search feature that allows the user to click a letter and see all the artists whose names begin with that letter. The issue (I believe) is that if the user enters a single letter in the search field, it is (as by design) returning all artists which contain that letter. E.g. enter the letter "a" an it might return results such as "Aerosmith", "Robert Plant", "Madonna", etc. If I am understanding the OP correctly, he wants the search field to work the same as selecting a letter when the user only uses a single letter in the search field. My guess is that there are different 'search' functions used for the search field vs. the letter selection. Two ways that I can think of implementing this are as follows: 1. Inspect the current back-end logic to determine the two processes used. For the search functionality, add a check to see if a single letter was entered. If so, redirect the functionality to the process that handles the letter selection. This would be the "best" solution, but requires you to be able to read and understand the logic as well as to know how to implement this change. 2. Add some JavaScript logic to the submit trigger for the search field. Same as above, check to see if a single letter was entered and, if so, call the same action as when a letter is selected. This would likely be easier to implement, but relies on client-side code. Not the best solution, IMO, but a workable one.
-
It's not even valid syntax !< The WHERE clause is where you include/exclude data based on conditions. The ordering logic will go in the ORDER BY clause. Based on your request and the query I'm not sure if you are trying to exclude records based on the date or if you are wanting the date used for the ordering logic. I think this may be what you want SELECT * FROM posts -- First order by the CONDITION of hot_topic = 'yes' AND created in last 7 days -- Secondarily order by the created date ORDER BY (hot_topic ='Yes' AND created > DATE_SUB(NOW(), INTERVAL 7 DAY)) DESC, created DESC LIMIT :per_page OFFSET :offset
-
I was going to do that, but after thinking about the "gaps" of 2 or more - decided it would likely be more complicated than generating a temporary array with all applicable indexes and then updating the values using the result set.
-
MsKazza, Are you saying there is only one record for each 'specials' value. I.e. there would only be one record for the value 1, one record for value 2, etc.? If so, you still need to follow Muddy_Funsters direction, but with some additional logic. 1. Create a query that sorts the records by the specials value 2. Create a variable to track the increment specials value 3. Create a loop to extract the results and compare the specials value from the result and the current record. Then determine whether to display the current record or an option to add a record. The one thing that is not clear is what are the maximum possible records. If it is only 6 (or a specific value) then you can hard code to that. Else, you can always add one "add" option after the last record. Here is one approach. This code is not tested <?php //Create and run query - sorting by specials value $query = "SELECT specials, product_code, product_name FROM products WHERE specials>0 AND product_publish='y' ORDER BY specials"; $result = mysqli_query($con, $query); //Create an array of 6 elements with index starting at 1 (with default FALSE values) $specials = array_fill(1, 6, FALSE); //Populate the valid specials from the result set while($row = mysqli_fetch_assoc($result)) { $specials[$row['specials']] = $row; } //Iterate through the array and generate the output $specialsOutput = ''; foreach($specials as $special) { if($special) { $specialsOutput .= "<td>{$special['product_code']}</td>\n"; $specialsOutput .= "<td>{$special['product_name']}</td>\n"; $specialsOutput .= "<td><span class=\"glyphicon glyphicon-trash\"></td>\n"; $specialsOutput .= "</tr>"; } else { $specialsOutput .= "<tr><td><input type=\"text\" id=\"special1code\"></td><td>add special</td></tr>"; } } ?> <form id="specials" name="specials" action="" method="post"> <table> <?php echo $specialsOutput; ?> </table> </form>
-
https://jsfiddle.net/10t3gzb9/4/