How to dynamically create object properties from an array in Javascript?

Is storing the name fields as a representation for a table identifier in either a PHP associative array, or in a Javascript object (client) a viable alternative for making an extra join in MySQL?

  • This is a question that I have wondered about for quite some time. When I need to make a query that is for example as follows: SELECT o.business_id, b.business_name, b.category  FROM owner_tbl o  INNER JOIN business_tbl b WHERE o.user_id = 1 Imagine that I need to display the name of the business category (defined in the business_tbl) in Javascript at the client, and I know upfront that the number of categories will not change quickly. I can prevent making an extra join with the category_tbl by storing the category names either: In an associative array in PHP; In an object in Javascript. Would you consider this to be bad practice? This type of situations often occurs: where you make a join, just to retrieve one 'name' field. Is there any alternative way that avoids making a join to speed up the retrieval?

  • Answer:

    On the server side, if you can avoid running the SQL query entirely, storing the results in $_SESSION or in a temporary file using perhaps <?php file_put_contents("./datafiles/query1.dat",serialize($myarray),LOCK_EX); // and $myarray = unserialize(file_get_contents("./datafiles/query1.dat")); ?> should gain a bit of speed. You can use filemtime to read when the file was last modified, in order to find out when the file is too old. <?php $filedate = filemtime("./datafiles/query1.dat"); echo "File changed ".date("F d Y H:i:s.", $filedate).", that was ".((now()-$filedate)/60/60)." hours ago."; ?> But if you can not avoid calling the query entirely, a join should be faster unless you are reading/writing to a data file that you need to use anyway. On the client side, you can use window.localStorage (https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage) to cache more or less unchanging data. In this case you are simply unloading the job to the client, boosting your own speed a tiny, tiny bit. This is however not very compatible since not all browsers support it, and not all users have JavaScript support turned on.

Lars Johan Olof Lidström at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.