-
Posts
4,704 -
Joined
-
Last visited
-
Days Won
179
Community Answers
-
kicken's post in Get the UPDATED row was marked as the answer
There is an example near the end of the documentation for last_insert_id. Something like this I am guessing.
$sql = " UPDATE $table SET item=?, id=LAST_INSERT_ID(id) WHERE id<10 ORDER BY id ASC LIMIT 1; "; //and then $last_id = mysqli_insert_id($conn); echo "Last inserted ID is: " . $last_id;
-
kicken's post in Listener not hearing me was marked as the answer
If the form is not added until the radio button is changed, the your code adding the event listeners cannot be run until after the radio button is changed either.
Alternatively, you add the event listener higher up in the DOM and check the element that triggered the event. For example:
document.getElementById("div2").addEventListener("click", displayDate); function displayDate(e){ if (e.target.tagName !== 'INPUT'){ return; } alert('Trigger'); }
You callback function is given an event object as it's parameter. That object has a property called target which is a reference to which DOM element triggered the event. Check that DOM element to see if it matches your criteria, in this case that it's an <input> element.
-
kicken's post in Define element within loop was marked as the answer
Use a multi-line closure and log the value.
divs.forEach(d => { console.log(d); d.classList.remove('active'); });
If you just want to change some colors on click, you can probably do that without JavaScript at all.
HTML:
<div tabindex="-1">First div</div> <div tabindex="-1">Second div</div> <div tabindex="-1">Third div</div> The tabindex attribute lets you make the div focusable. Having the div focusable allows you to use the :focus css pseudo class.
CSS:
div { margin: 2rem; padding: 1rem; border: 2px solid #00F; } div[tabindex]:focus { background: #000; color: #fff; }
-
kicken's post in How to properly restart gameloop/animation? was marked as the answer
Set your old timestamp variable to null when the game is started/restarted.
this.oldTimeStamp = null; Then in your game loop function, check if it's null and if so store the provided timestamp.
if (this.oldTimeStamp===null){ this.oldTimeStamp=timeStamp; } This way your game always starts out at 0 for seconds passed. Currently, your first iteration when the page loads is essentially random as it depends on how long it takes for the browser to run the first game loop after starting the page.
-
kicken's post in Add (sum) currency values was marked as the answer
Formatting values should always be a last-step operation. You want to structure your code so the prices remain as numbers and you can do whatever operations on them you need to do, then only format them right before you display them, for example directly in your template if possible.
$price1 = 30; $price2 = 74.99; $bundle = $price1 + $price2; //...anything else //When everything is done and you're ready to display echo getMoneyUSD($price1); echo getMoneyUSD($price2); echo getMoneyUSD($price3); Also, you should know that floating point math can lead to issues due to lack of precision. A common way to avoid these issues is to work with your prices as integers (ie, number of cents) then convert them to decimals as part of the formatting process. Alternatively, you could find a library for dealing with currency values that handles such issues for you.
-
kicken's post in Just curious to know why was marked as the answer
Assuming mysql, Your tables may be using the MyISAM engine which does not support transactions. You should be using InnoDB unless you have a specific reason not to.
-
kicken's post in Php Mysql IP Ban error in script was marked as the answer
Your file has a invalid character in it that needs to be removed. Try deleting the line and re-typing it. Don't copy/paste or you'll copy/paste the character as well.
-
kicken's post in Trouble with Xdebug Breakpoint using Sublime Text was marked as the answer
In order to use step debugging, xdebug.mode needs to contain debug.
If it still does not work after adding that, try setting xdebug.start_with_request to yes.
I have not used either sublime or that browser extension, so not sure if they need anything special.
-
kicken's post in Inserting multiple values for one user in new column was marked as the answer
Sounds like you just want an update query. For example
update users_table set reqid=75 where username='joe' If that's not what you want, then you may need to try and explain again differently.
-
kicken's post in How to get where is the old row in new query? was marked as the answer
Before anything else, you need to add an ORDER BY clause to your query so that you can ensure a consistent order of your results. Without an ORDER BY clause, the database server is allowed to return the rows in whatever order it wants, usually that's just whatever order it finds them in as it scans the indexes/tables. As you add/remove data that order will change.
Once you have your results ordered in a specific way, you can count the number of records that come before a specific row by running a query with a where condition of theOrderByColumn <= yourCurrentRowsOrderByColumn. For example.
SELECT id,path, subCategoryId FROM `files` WHERE categoryId=5 AND subCategoryId=15 ORDER BY id; SELECT COUNT(*) FROM files WHERE categoryId=5 AND subCategoryId=15 AND id <= 307
-
kicken's post in What is it for ReflectionAttribute::IS_INSTANCEOF was marked as the answer
Look at the documentation for getAttributes(). There is a flags parameter which is where you use the IS_INSTANCEOF constant.
-
kicken's post in Code doesn't crash but gives no result was marked as the answer
Your analyzePage function is not returning a value, so your $analysis variable will be null. If you have PHP's error reporting turned up all the way, and are on a modern version of PHP, you should be seeing a warning about not being able to use foreach on a null value.
On an unrelated note:
This could simply be return $content; There is no need for the check against false there since if it is false, you will just return false.
-
kicken's post in access to the target of an attribute was marked as the answer
This is where the misunderstanding of what attributes are and are for seems to come in. Attributes apply to the class itself. The only way to make a connection between a specific instance of a class and that classes attributes is when you use reflection on the instance to look up it's class and associated attributes. This process only works one way: instance -> class -> attributes. You cannot go backwards the other way: attribute -> class -> instance.
-
kicken's post in Is there a correct way to exit JSON? was marked as the answer
It's a lot like using relative file paths rather than absolute paths in your PHP code or HTML links.
Rather than trying to reference everything with an ID and getElementById, you instead reference elements relative to other elements using things like parentElement, nextElementSibling, previousElementSibling, querySelector, etc. You can usually reference some parent element (either by ID or a class name) then locate child elements either via their position in the HTML structure or class names.
Without knowing what your HTML is, I can't provide and specific recommendation. Here is an example though:
window.addEventListener('DOMContentLoaded', () => { const list = document.getElementById('option-list'); list.addEventListener('change', (e)=>{ const checkbox=e.target; const description=checkbox.parentElement.nextElementSibling; description.style.display=checkbox.checked?'block':'none'; }); }); Paired with the HTML
<ul id="option-list"> <li> <label><input type="checkbox"> Test option 1</label> <div class="description">Some description for option 1</div> </li> <li> <label><input type="checkbox"> Test option 2</label> <div class="description">Some description for option 2</div> </li> <li> <label><input type="checkbox"> Test option 3</label> <div class="description">Some description for option 3</div> </li> <li> <label><input type="checkbox"> Test option 4</label> <div class="description">Some description for option 4</div> </li> </ul> The JavaScript code only references the parent list element by and ID and listens for a change event on it (which will be triggered by a change in any child). When that change event is triggered, the input element that triggered it can be references using e.target. Looking at the HTML structure, the div that should be shown/hidden is a sibling to the inputs parent, so a reference to it can be obtained by first getting the input parent (parentElement) then it's next sibling(nextElementSibling).
With this code, you can add as many <li> elements following that structure as you want and they will all work. No need to generate unique IDs for each and add custom event handlers to each one.
For exactly the reason you created this thread, and more. ID's must be unique, so if you have some repeating structure you need to find some way of generating unique IDs and reference those IDs in your code. Often times, using class names or other more natural references are better and avoid these issues.
-
kicken's post in Using submit to open a new page in a new window was marked as the answer
You can use target on a form tag also.
<form method="post" target="_blank"> <input type="submit"> </form>
-
kicken's post in Book about IIS and PHP? was marked as the answer
The server software you use is not that relevant to developing in PHP. Installing and configuring PHP itself to run will vary based on the server software, but once that is done, your scripts run the same regardless of the server. I do all my local development work using Apache, but the production site is hosted on IIS. The PHP code is all the same, there's nothing in it that cares which server software is being used.
The server configuration required to get PHP installed and running, and to configure specific things needed by the site vary between the two of course. For example, IIS doesn't understand .htaccess files, it has it's own web.config file for dynamic site configuration settings. The way the domain and document roots are setup is different as well, but that's general server administration stuff and not PHP specific. For that information you'd just find IIS or Apache documentation / tutorials.
If your goal is just to learn PHP, then you'd probably have an easier time just setting up apache since a lot of documentation references it. If your goal is to learn IIS, then seek out IIS documentation in general rather than IIS+PHP specific stuff.
-
kicken's post in Create session with expirey that updates on each refresh was marked as the answer
If you want to change the session cookie parameters, you need to do so before you call session_start(), not after.
-
kicken's post in Does this javascript code cause stateless or stateful protocol request? was marked as the answer
Your JavaScript code doesn't involve a request at all, other than the one to initially load the page which is going to be a standard stateless HTTP request. The only stateful protocol you would possibly end up using in JavaScript code is a WebSocket. The rest of the web revolves around stateless HTTP requests.
That blog post has less to do with HTTP and more to do with applications. HTTP is stateless, but most web applications are not as they rely upon session data to track who is logged in or other details. That session data makes the application as a whole stateful even if the individual HTTP requests are not.
-
kicken's post in Server Resets while page is loading was marked as the answer
IIS has various timeout settings. If this is a large import, you shouldn't be doing it through a web interface like phpMyAdmin, long running requests don't usually work out well. You'd be better off using the command line tools to do the import or a tool like MySQL Workbench that can connect directly to the database and run the import.
-
kicken's post in Php Mysql 2 if statements for one hide echo was marked as the answer
The syntax of an if statement looks like this:
if (some condition){ //do stuff } The some condition part could be a single comparison, or multiple comparisons joined with logical operators. Note though, how there needs to be a set of parenthesis surrounding the entire condition. Now, look at your attempt:
if (strpos($row["message"], 'And Click') == true) && ($viewspec_pref == "no") { You have your two conditions combined with the logical AND operator. What you're missing through, is the parenthesis that surrounds the entire combined condition. Instead, you put parenthesis around the individual conditions (which is ok, but unnecessary). Add the required parenthesis around the entire condition and you'll have something that is syntactically valid.
It is a potential issue. The solution, which was never really pointed out, is that you need to strictly compare against false to determine if a match was found or not. Using a loose comparison against true will fail if your message starts with the target string (since strpos would return zero, and zero is falsely).
if (strpos($row["message"], 'And Click') !== false && $viewspec_pref === "no") { It can generally be worth getting in the habit of using the strict comparison (identical) operators whenever possible, as it helps avoid such surprise outcomes.
If you are using PHP 8.0 or better, you can avoid this whole problem by using str_contains instead.
-
kicken's post in Loading PDF files into a sql database was marked as the answer
Try
$stmt->bindParam(':fileContent', $fileContent, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
-
kicken's post in php class autoload question was marked as the answer
There are no internals of spl_autoload_register with regards to the locating and loading of a class. All the details of how that is done is up to the function you provide. All spl_autoload_register does is add your function to a list of functions that get called when an unknown class is referenced. Your function gets the fully qualified name of the class and has to use that to define that class, typically by converting the name to a file location and including that file.
Your example essentially just uses the class name as-is as a file path and attempts to include that file. Since your class is defined as Hello then you get a filename of Hello.class.php with a capital H. Your actual filename however seems to be hello.class.php with a lower-case H. On a case-insensitive filesystem such as windows' ntfs, this would be fine and the file would be loaded. On a case-sensitive filesystem such as linux ext4, this is a problem and the file will fail to load.
As mentioned, typically one would just use composer to handle class autoloading rather than defining your own function. Combine it with the PSR-4 standard (and ensure you get your case correct) and you mostly don't have to think about it at all.
-
kicken's post in Centering the popup form was marked as the answer
Been a long time since I used a positioned popup window. Had to check the docs for the right options.
You can center the popup on the screen by setting the top / left options. These control the top-left corner of the window, so to get it truly center you have to calculate the right offset. There's a standard formula for this.
centerPoint = (sizeOfContainer - sizeOfThing) / 2 For this case, your sizeOfContainer is the screen width/height and the sizeOfThing are your popup window's width/height. Run that formula for each to get your top/left values and set them in the window options.
const popupWidth = 400, popupHeight = 800; let top = (window.screen.height - popupHeight)/2; let left = (window.screen.width - popupWidth)/2; const win = window.open('', 'formpopup', 'width='+popupWidth+',height='+popupHeight+',resizable,scrollbars,top='+top+',left='+left); The final result may be slightly off (mostly in the height axis) due to the window UI elements since they are not part the calculation. The width/height you specify is for the content area of the window, the UI elements are added on top of that. If the slight offset bugs you, you can fix it after opening the window by re-calculating the offset using the window's outerWidth and outerHeight values for sizeOfThing, then using it's moveTo function to re-position it.
top = (window.screen.height - win.outerHeight)/2; left = (window.screen.width - win.outerWidth)/2; win.moveTo(left, top); That may create a noticeable jump after the window opens though.
-
kicken's post in variable functions was marked as the answer
PHP allows extra values to be passed to a function. You can use func_get_args to obtain these values within the function and do something with them. This is the original way of creating a variable-length argument function.
-
kicken's post in Why does window.load function triggers "click" event of elements? was marked as the answer
In that line, you are not assigning the toggleBtn function as an on-click event handler. You are executing that function now and assigning whatever value it returns (which is nothing) as your on-click handler.
You need to wrap it an anonymous function which is passed to addEventListener as the click handler.
item.addEventListener('click', function(){ toggleBtn(item,index,arr); }, false)