SELECT not working properly within PHP inside JavaScript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • geniajanssen
    New Member
    • Jan 2007
    • 12

    SELECT not working properly within PHP inside JavaScript

    Hi there:

    I cannot get the code below to work properly. It works fine on the first loop but the next times around "$querySQL = 'SELECT * FROM host_index'" returns the wrong value.

    Can somebody help me out?
    [php]
    <?php
    require_once('c onnections/radiolightstrea m.php');

    mysql_select_db ($database_radi olightstream, $radiolightstre am);
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitl ed Document</title>
    <SCRIPT LANGUAGE="JavaS cript">

    <SCRIPT LANGUAGE="JavaS cript">

    // ***** Modify the messages here ***** //
    var Message = new Array(3);
    Message[0]=
    "<?php
    $querySQL = 'SELECT * FROM host_index'; // get next host index
    $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
    $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
    $row_result = mysql_fetch_arr ay ($result);
    echo $row_result['next_host'].'<p>';
    $host_id = $row_result['next_host'] + 1; // actual host id
    ?>";
    Message[1]=
    "<?php
    $querySQL = 'SELECT * FROM hosts WHERE approved=1 AND paid=1';
    $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
    $num_hosts = mysql_numrows($ result);
    mysql_data_seek ($result, $row_result['next_host']) or die(mysql_error ());
    $row_host_resul t = mysql_fetch_arr ay ($result);
    echo $row_host_resul t[show_title].'<p>';
    ?>";
    Message[2]=
    '<?php
    $next_host = $host_id % $num_hosts; // update pointer
    $querySQL = "UPDATE host_index SET next_host=$next _host";
    $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
    echo $querySQL."<p>" ;
    ?>';

    var nCount = 0;
    function rotateSpan1()
    {
    Span1.innerHTML =Message[nCount];
    nCount++;
    if(nCount>Messa ge.length-1) nCount=0;
    setTimeout("rot ateSpan1()",500 0);
    }
    function showSpan1(obj)
    {
    Span1.innerHTML =obj
    }

    </SCRIPT>
    </head>

    <body>
    <div id=Span1></div>
    <SCRIPT LANGUAGE="JavaS cript">
    rotateSpan1();
    </SCRIPT>
    </body>
    </html>[/php]
    Genia
    Last edited by ronverdonk; Feb 6 '07, 07:43 PM. Reason: enclosing code within tags
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    Please read the Posting Guidelines before you post in this forum!. Especially the part about enclosing posted code within code or php tags!

    MODERATOR

    Comment

    • geniajanssen
      New Member
      • Jan 2007
      • 12

      #3
      I'm not usre what I did wrong. Please explain and I will fix.

      Genia

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        Originally posted by geniajanssen
        I'm not usre what I did wrong. Please explain and I will fix.

        Genia
        Then do as I requested: read the Posting Guidelines:
        POSTING GUIDELINES

        Please follow these guidelines when posting questions or answers. Submitting clear and concise questions allows those reading to understand your problem and respond easily.
        Post your question in a relevant forum
        Give a clear title to your question (Need help or Have a problem are no clear descriptions)
        Give as much detail as possible
        Clear explanation (in english)
        Platform / OS / Version
        Language
        Source code
        Input used
        Error Codes
        Write in clear concise language, using correct grammar and spelling
        For code, use the tag buttons at the top of the edit area:
        PHP Code:

        Use [PHP] and [/PHP ] tags around your PHP code


        HTML Code:
        Use [HTML] and [/HTML ] tags around your HTML code

        Code:
        Use [CODE] and [/CODE ] tags around other code

        Homework
        You will learn a lot more by attempting the problem yourself and asking for help with the bits that are not working. And you will be more likely to get help if you appear to have made an attempt at the problem yourself.
        Lastly, it is common decency to acknowledge to your fellow members that you were helped by them or that your problem was solved (or not) thanks to their effort.

        Comment

        • geniajanssen
          New Member
          • Jan 2007
          • 12

          #5
          Hi there:

          I cannot get the code below to work properly. It works fine on the first loop but the next times around "$querySQL = 'SELECT * FROM host_index'" returns the wrong value.

          Specifically, here is what happens...

          The first time 'SELECT next_host FROM host_index' is executed, it works properly. Let's say it is '0';

          The following command 'SELECT * FROM hosts WHERE approved=1 AND paid=1' also works properly. Then mysql_data_seek ($result, 0]) or die(mysql_error ()); works properly.

          Finally, "UPDATE host_index SET next_host=1" works properly. I verified this using phpMyAdmin and next_host in the table host_index is now set to '1'.

          The problem starts with subsequent loops in this function.

          The next time 'SELECT next_host FROM host_index' is executed, it does not work properly. It says it is '0' but it is really set to 'i' .

          This is the problem: the table value (set to '1') is correct but the SELECT command is not working properly because it returns '0' in all subsequent loops and there is no error message.

          Can somebody help me out?
          [php]
          <?php
          require_once('c onnections/radiolightstrea m.php');

          mysql_select_db ($database_radi olightstream, $radiolightstre am);
          ?>

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
          <html xmlns="http://www.w3.org/1999/xhtml">
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
          <title>Untitl ed Document</title>
          <SCRIPT LANGUAGE="JavaS cript">

          // ***** Modify the messages here ***** //
          var Message = new Array(3);
          Message[0]=
          "<?php
          $querySQL = 'SELECT next_host FROM host_index'; // get next host index
          $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
          $row_result = mysql_fetch_arr ay ($result);
          echo $row_result['next_host'].'<p>';
          $host_id = $row_result['next_host'] + 1; // actual host id
          ?>";
          Message[1]=
          "<?php
          $querySQL = 'SELECT * FROM hosts WHERE approved=1 AND paid=1';
          $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
          $num_hosts = mysql_numrows($ result);
          mysql_data_seek ($result, $row_result['next_host']) or die(mysql_error ());
          $row_host_resul t = mysql_fetch_arr ay ($result);
          echo $row_host_resul t[show_title].'<p>';
          ?>";
          Message[2]=
          '<?php
          $next_host = $host_id % $num_hosts; // update pointer
          $querySQL = "UPDATE host_index SET next_host=$next _host";
          $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
          echo $querySQL."<p>" ;
          ?>';

          var nCount = 0;
          function rotateSpan1()
          {
          Span1.innerHTML =Message[nCount];
          nCount++;
          if(nCount>Messa ge.length-1) nCount=0;
          setTimeout("rot ateSpan1()",500 0);
          }
          function showSpan1(obj)
          {
          Span1.innerHTML =obj
          }

          </SCRIPT>
          </head>

          <body>
          <div id=Span1></div>
          <SCRIPT LANGUAGE="JavaS cript">
          rotateSpan1();
          </SCRIPT>
          </body>
          </html>
          [/php]

          Genia

          Comment

          • geniajanssen
            New Member
            • Jan 2007
            • 12

            #6
            More information...

            The output is

            Loop 1:

            0 (correct)
            Tazz and Paula Show (correct)
            1 (correct - and database is updated correctly)

            Loop 2:

            0 (incorrect - should be 1 - however, the database has the correct value and SELECT is not working properly)
            Tazz and Paula Show (read correctly but wrong value because the SELECT above did not work properly)
            1 (wrong value because the SELECT above did not work properly)

            This will repeat for all subsequent loops.

            THE CORRECT OUTPUT SHOULD BE...

            Loop 1:

            0
            Tazz and Paula Show
            1

            Loop 2:

            1
            Tisha Rivas
            2

            Loop 3:

            2
            Adam Atman
            0

            Loop 4:

            0
            Tazz and Paula Show
            1

            and so on...

            The problem is with SELECT not working properly after the first loop.

            Genia

            Comment

            • ronverdonk
              Recognized Expert Specialist
              • Jul 2006
              • 4259

              #7
              I can't tell exactly, but the answer may probably be found in a thread that addresses a similar problem. See PHP inside JS - Not working 4 me

              Ronald :cool:

              Comment

              • geniajanssen
                New Member
                • Jan 2007
                • 12

                #8
                That is exactly the problem that I am having.

                Does anyone out there have a workaround with AJAX.

                Genia

                Comment

                • ronverdonk
                  Recognized Expert Specialist
                  • Jul 2006
                  • 4259

                  #9
                  There is no Ajax work-around readily available, but we can assist you in making one.
                  3 questions before we continue:
                  1. what is the purpose of this script? Looks like an endless loop to me.
                  2. if you use this loop within the server script, how do you propose to terminate it?
                  3. have you thought about the load/strain on your server?

                  Ronald :cool:

                  Comment

                  • geniajanssen
                    New Member
                    • Jan 2007
                    • 12

                    #10
                    That is actually a snippet of code.

                    If you go to www.radiolightstream.com, you will notice that the right column refreshes every time the page is refreshed or another page is reloaded.

                    What my client wants to to refresh the right column every 20 seconds.

                    I don't seem to find a way to do this in PHP, so I guess I have to use JavaScript. However, with one being server-side and one being client-side, it seems that the first SELECT is only executing properly once.

                    Below is the actual PHP script:

                    [php]
                    <?php
                    function asc2hex ($temp)
                    {
                    $len = strlen ($temp);
                    for ($i =0; $i < $len; $i++)
                    $data .= sprintf ("%02x", ord (substr ($temp,$i,1)));
                    return $data;
                    }

                    function hex2asc ($temp)
                    {
                    $len = strlen ($temp);
                    for ($i = 0; $i < $len; $i += 2)
                    $data .=chr (hexdec (substr ($temp, $i, 2)));
                    return $data;
                    }

                    function get_featured_ho st ($radiolightstr eam)
                    {
                    $querySQL = "SELECT next_host FROM host_index"; // get next host index
                    $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
                    $row_result = mysql_fetch_arr ay ($result);
                    $host_id = $row_result['next_host'] + 1; // actual host id

                    $querySQL = "SELECT * FROM hosts WHERE approved=1 AND paid=1";
                    $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
                    $num_hosts = mysql_numrows($ result);
                    mysql_data_seek ($result, $row_result['next_host']) or die(mysql_error ());
                    $row_host_resul t = mysql_fetch_arr ay ($result);

                    $row_result['next_host']++; // update pointer
                    $row_result['next_host'] %= $num_hosts;

                    $querySQL = "UPDATE host_index SET next_host=$row_ result[next_host]"; // set next resource index
                    $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
                    ?>
                    <table width="100%" border="0" cellspacing="0" cellpadding="1" >
                    <tr align="center">
                    <td>
                    <?php
                    if ($row_host_resu lt['photo'] != NULL)
                    {
                    $description = hex2asc($row_ho st_result['photo']); // convert back to binary data

                    $picture = "guests/".$row_host_res ult['first_name'].$row_host_resu lt['last_name'].".jpg";

                    // create a temporary JPG file on the server so that we can later read the file and determine its size
                    $fp = fopen ($picture, "w");
                    fwrite ($fp, $description);
                    fclose ($fp);

                    // resize if picture is too large
                    $size = GetImageSize($p icture);
                    $width = $size[0];
                    $height = $size[1];
                    $x_ratio = 150 / $width;
                    $y_ratio = 150 / $height;
                    if ( ($width <= 150) && ($height <= 150) )
                    {
                    $tn_width = $width;
                    $tn_height = $height;
                    }
                    else if (($x_ratio * $height) < 150)
                    {
                    $tn_height = ceil($x_ratio * $height);
                    $tn_width = 150;
                    }
                    else
                    {
                    $tn_width = ceil($y_ratio * $width);
                    $tn_height = 150;
                    }
                    ?>
                    <br>
                    <img src="<?php print $picture; ?>" width=<?php print $tn_width; ?>
                    height=<?php print $tn_height; ?> alt="<?php echo StripSlashes ($row_host_resu lt[show_title]); ?>" border="0">
                    <?php
                    }
                    ?>
                    [/php]

                    What I really want to do is execute this PHP script every 20 seconds.

                    I hope that helps.

                    Genia

                    Comment

                    • ronverdonk
                      Recognized Expert Specialist
                      • Jul 2006
                      • 4259

                      #11
                      I have looked at the code and your intention, and I came up with the following scripts.
                      1. ajax.js : the Ajax code that handles the requests to the server
                      2. a.php: the routine that is executed and contains the JS code. For this I reworked your code from your first post in this thread.
                      3. getNextImage.ph p: the server routine that returns the entire display image and text to the A.PHP script. For this I reworked your code that you showed in the last post in this thread.

                      Now I, obviously. was not able to test with an actual image database, as you use. But I have tested the 20 second rotation and the server action. For this I just add a variable named 'no' to the JS code. This variable is incremented and passed to the server script each 1 second. The server script then echoes it and exits. The Ajax routine captures it and displayes it at your screen. So, when you run this code, you will see an update to your screen every 1 seconds.

                      Since the ajax.js file is too large to show here, I just show the reworked client and server programs. If you want the Ajax.js file, just send me a private message (click on my name at the top of this post) with your email address and I'll send it to you via email.

                      Try it out and have fun.

                      Script a.php:
                      [php]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
                      <html xmlns="http://www.w3.org/1999/xhtml">
                      <head>
                      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                      <script type="text/javascript" src="ajax/ajax.js"></script>
                      <title>Spanne r</title>

                      <script language="JavaS cript">
                      var ajax = new sack();
                      var no = 0;
                      function rotateIt() {
                      ajax.requestFil e = 'getNextImage.p hp?no='+no;
                      ajax.onCompleti on = rotateSpan;
                      ajax.runAJAX();
                      setTimeout("rot ateIt()",1000);
                      }

                      function rotateSpan() {
                      document.getEle mentById("Span" ).innerHTML = ajax.response;
                      no = no +1;
                      }
                      </script>
                      </head>
                      <body>
                      <div id=Span></div>
                      <script language="JavaS cript">
                      rotateIt();
                      </script>
                      </body>
                      </html>[/php]

                      Script getNextImage.ph p:
                      [php]<?php
                      // THIS IS JUST FOR TESTING PURPOSES
                      $i=$_GET['no'];
                      echo "A TEST LINE NO $i";
                      exit;

                      // Make a MySQL Connection
                      require_once('c onnections/radiolightstrea m.php');
                      mysql_select_db ($database_radi olightstream, $radiolightstre am);

                      // get the next picture
                      get_featured_ho st ($radiolightstr eam);
                      exit;

                      // FUNCTIONS
                      function asc2hex ($temp)
                      {
                      $len = strlen ($temp);
                      for ($i =0; $i < $len; $i++)
                      $data .= sprintf ("%02x", ord (substr ($temp,$i,1)));
                      return $data;
                      }

                      function hex2asc ($temp)
                      {
                      $len = strlen ($temp);
                      for ($i = 0; $i < $len; $i += 2)
                      $data .=chr (hexdec (substr ($temp, $i, 2)));
                      return $data;
                      }

                      function get_featured_ho st ($radiolightstr eam)
                      {
                      $querySQL = "SELECT next_host FROM host_index"; // get next host index
                      $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
                      $row_result = mysql_fetch_arr ay ($result);
                      $host_id = $row_result['next_host'] + 1; // actual host id

                      $querySQL = "SELECT * FROM hosts WHERE approved=1 AND paid=1";
                      $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());
                      $num_hosts = mysql_numrows($ result);
                      mysql_data_seek ($result, $row_result['next_host']) or die(mysql_error ());
                      $row_host_resul t = mysql_fetch_arr ay ($result);

                      $row_result['next_host']++; // update pointer
                      $row_result['next_host'] %= $num_hosts;

                      $querySQL = "UPDATE host_index SET next_host=$row_ result[next_host]"; // set next resource index
                      $result = mysql_query($qu erySQL, $radiolightstre am) or die(mysql_error ());

                      echo '<table width="100%" border="0" cellspacing="0" cellpadding="1" >';
                      echo '<tr align="center"> ';
                      echo '<td>';

                      if ($row_host_resu lt['photo'] != NULL)
                      {
                      $description = hex2asc($row_ho st_result['photo']); // convert back to binary data

                      $picture = "guests/".$row_host_res ult['first_name'].$row_host_resu lt['last_name'].".jpg";

                      // create a temporary JPG file on the server so that we can later read the file and determine its size
                      $fp = fopen ($picture, "w");
                      fwrite ($fp, $description);
                      fclose ($fp);

                      // resize if picture is too large
                      $size = GetImageSize($p icture);
                      $width = $size[0];
                      $height = $size[1];
                      $x_ratio = 150 / $width;
                      $y_ratio = 150 / $height;
                      if ( ($width <= 150) && ($height <= 150) )
                      {
                      $tn_width = $width;
                      $tn_height = $height;
                      }
                      else if (($x_ratio * $height) < 150)
                      {
                      $tn_height = ceil($x_ratio * $height);
                      $tn_width = 150;
                      }
                      else
                      {
                      $tn_width = ceil($y_ratio * $width);
                      $tn_height = 150;
                      }

                      echo "<br><img src='$picture' width='$tn_widt h' height='$tn_hei ght' alt='".
                      StripSlashes ($row_host_resu lt[show_title])."' border='0'>";
                      }
                      }
                      ?>[/php]
                      Ronald :cool:

                      Comment

                      • ronverdonk
                        Recognized Expert Specialist
                        • Jul 2006
                        • 4259

                        #12
                        Now that you have all the code you need to accomplish what I think you want to accomplish, could you share the results with our member community? Thank you.

                        Ronald :cool:

                        Comment

                        • geniajanssen
                          New Member
                          • Jan 2007
                          • 12

                          #13
                          Ronald:

                          I cannot get the scripts to work. What EXACTLY to I need to do to test. I have already downloaded ajax.js.

                          Genia

                          Comment

                          • geniajanssen
                            New Member
                            • Jan 2007
                            • 12

                            #14
                            My mistake. I had the ajax.js file in the wrong directory. I have everything working now. Check out www.radiolights tream.com in the right column. Quite a combination with HTML, PHP, MySQL JavaScript and Ajax!

                            Thanks for all of your help, Ronald.

                            Genia

                            Comment

                            • ronverdonk
                              Recognized Expert Specialist
                              • Jul 2006
                              • 4259

                              #15
                              Wish I had helped better because I don't see the right column change every 20 seconds as you required! Only after a page reload.

                              Are you sure you have the right code in?

                              Ronald :cool:

                              Comment

                              Working...