Results 1 to 8 of 8
  1. #1
    Senior Member
    Join Date
    Mar 2011
    Rep
    Posts
    154
    Country
    Norway

    Fetching mysql data and display them [multiple row] on website using PHP, jQuery ajax

    Currently working on a web exam on school. And I have to dig a bit into web programming to make my site look cool.

    I want to fetch data from a mysql server and display them on the website in a list (like a very simplified highscore).

    Here is a sample using phpmyadmin:

    Query used from phpmyadmin to get the desired info/results:
    Code :
    SELECT b.skap_id AS  'Skap Nummer', t.tittel AS  'Tittel', p.platform_tittel AS  'Platform'
    FROM battlestation b, tittel t, platform p
    WHERE b.tittel_id = t.tittel_id
    AND p.platform_id = t.platform_id
    AND skap_id =1
    ORDER BY tittel
    LIMIT 0 , 30

    I have been googling around a abit, and trying to learn some samples done with javascript/jquery ajax and php.

    Here is what I got so far: (scripts taken from Using JQuery AJAX and php to fetch data from a mysql database | OpenEnergyMonitor )

    api.php:
    PHP Code:
    <?php 

      
    //--------------------------------------------------------------------------
      // Example php script for fetching data from mysql database
      //--------------------------------------------------------------------------
      
    $host "localhost";
      
    $user "test";
      
    $pass "test";

      
    $databaseName "nith";
      
    $tableName "battlestation";

      
    //--------------------------------------------------------------------------
      // 1) Connect to mysql database
      //--------------------------------------------------------------------------
      //include 'DB.php';
      
    $con mysql_connect($host,$user,$pass);
      
    $dbs mysql_select_db($databaseName$con);

      
    //--------------------------------------------------------------------------
      // 2) Query database for data
      //--------------------------------------------------------------------------
      
    $result mysql_query("SELECT * FROM $tableName");          //query
      
    $array mysql_fetch_row($result);                          //fetch result    

      //--------------------------------------------------------------------------
      // 3) echo result as json 
      //--------------------------------------------------------------------------
      
    echo json_encode($array);

    ?>
    client.php:
    PHP Code:
    <!---------------------------------------------------------------------------
    Example client script for JQUERY:AJAX -> PHP:MYSQL example
    ---------------------------------------------------------------------------->

    <
    html>
      <
    head>
        <
    script language="javascript" type="text/javascript" src="motor/js/jquery.js"></script>
      </head>
      <body>

      <!-------------------------------------------------------------------------
      1) Create some html content that can be accessed by jquery
      -------------------------------------------------------------------------->
      <h2> Client example </h2>
      <h3>Output: </h3>
      <div id="output">this element will be accessed by jquery and this text replaced</div>

      <script id="source" language="javascript" type="text/javascript">

      $(function () 
      {
        //-----------------------------------------------------------------------
        // 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
        //-----------------------------------------------------------------------
        $.ajax({                                      
          url: 'api.php',                  //the script to call to get data          
          data: "",                        //you can insert url argumnets here to pass to api.php
                                           //for example "id=5&parent=6"
          dataType: 'json',                //data format      
          success: function(data)          //on recieve of reply
          {
            var bsid = data[0];              //get id
            var skapid = data[1];           //get name
            var tittelid = data[2];        //get tittelid
            //--------------------------------------------------------------------
            // 3) Update html content
            //--------------------------------------------------------------------
            $('#output').html("<b>Battlestation id: </b>"+bsid+"<b> skap id: </b>"+skapid+"<b> tittel id: </b>"+tittelid); //Set output element html
            //recommend reading up on jquery selectors they are awesome 
            // http://api.jquery.com/category/selectors/
          } 
        });
      }); 

      </script>
      </body>
    </html> 
    Results so far:


    Goals:

    1. Make it successfully connect to DB and fetch data from simple "select all from table" query. [success].
    2. Make it display all rows query is fetching. [Success].
    3. Make a query /script to display the desired information. (see first picture from phpmyadmin). [success].

    If you can help me tweak this script or if you have some sample script, does not have to be in any relation to javascript/jquery/ajax I would be thankful.
    Last edited by Brannfjell; 21-03-2012 at 22:55.

  2. #2
    Admin
    Join Date
    Sep 2010
    Rep
    Posts
    3,404
    Country
    Norway
    Code :
    $array = array();
    $row = mysql_fetch_row($result);
    while($row) {
        $array[] = $row;
        $row = mysql_fetch_row($result);
    }
    // (...)
    echo json_encode($array);
    And loop over the list in javascript.

    (Note: mysqli is nicer!)

    Code :
    for(var i = 0; i < data.length; i++) {
         $('#output').append("<b>Battlestation id: </b>"+data[i][0]+"<b> skap id: </b>"+data[i][1]+"<b> tittel id: </b>"+data[i][2]);
    }
    Last edited by Stian; 21-03-2012 at 15:12.
    I generally don't answer questions in PMs. Post it at the forum instead!

    His personality is so magnetic that he's unable to carry credit cards. He never say something taste like chicken... not even chicken. He's a lover, not a fighter, but he is also a fighter so don't get any ideas!

    Find out what you don't do well in life, and don't do that thing

  3. #3
    Senior Member
    Thread Starter

    Join Date
    Mar 2011
    Rep
    Posts
    154
    Country
    Norway
    Code :
    Client example
     
    Output:
     
    this element will be accessed by jquery and this text replacedBattlestation id: 1 skap id: 1 tittel id: 1
    Battlestation id: 2 skap id: 1 tittel id: 2
    Battlestation id: 3 skap id: 1 tittel id: 3
    Battlestation id: 4 skap id: 1 tittel id: 4
    Battlestation id: 5 skap id: 1 tittel id: 5
    Battlestation id: 6 skap id: 1 tittel id: 6
    Battlestation id: 7 skap id: 1 tittel id: 7
    Battlestation id: 8 skap id: 1 tittel id: 8
    Battlestation id: 9 skap id: 1 tittel id: 9
    Battlestation id: 10 skap id: 1 tittel id: 10
    Battlestation id: 11 skap id: 1 tittel id: 11
    Battlestation id: 12 skap id: 1 tittel id: 12
    Battlestation id: 13 skap id: 1 tittel id: 13
    Battlestation id: 14 skap id: 2 tittel id: 14
    Battlestation id: 15 skap id: 3 tittel id: 14
    Battlestation id: 16 skap id: 4 tittel id: 14
    Battlestation id: 17 skap id: 5 tittel id: 14
    Battlestation id: 18 skap id: 2 tittel id: 15
    Battlestation id: 19 skap id: 2 tittel id: 16
    Battlestation id: 20 skap id: 4 tittel id: 16
    Battlestation id: 21 skap id: 5 tittel id: 16
    Battlestation id: 22 skap id: 2 tittel id: 17
    Battlestation id: 23 skap id: 3 tittel id: 17
    Battlestation id: 24 skap id: 4 tittel id: 17
    Battlestation id: 25 skap id: 5 tittel id: 17
    Battlestation id: 26 skap id: 2 tittel id: 18
    Battlestation id: 27 skap id: 5 tittel id: 18
    Battlestation id: 28 skap id: 2 tittel id: 19
    Battlestation id: 29 skap id: 2 tittel id: 20
    Battlestation id: 30 skap id: 2 tittel id: 21
    Battlestation id: 31 skap id: 2 tittel id: 22
    Battlestation id: 32 skap id: 2 tittel id: 23
    Battlestation id: 33 skap id: 2 tittel id: 24
    Battlestation id: 34 skap id: 5 tittel id: 24
    Battlestation id: 35 skap id: 2 tittel id: 25
    Battlestation id: 36 skap id: 5 tittel id: 25
    Battlestation id: 37 skap id: 2 tittel id: 26
    Battlestation id: 38 skap id: 2 tittel id: 27
    Battlestation id: 39 skap id: 2 tittel id: 28
    Battlestation id: 40 skap id: 2 tittel id: 29
    Battlestation id: 41 skap id: 2 tittel id: 30
    Battlestation id: 42 skap id: 3 tittel id: 31
    Battlestation id: 43 skap id: 3 tittel id: 32
    Battlestation id: 44 skap id: 3 tittel id: 33
    Battlestation id: 45 skap id: 4 tittel id: 33
    Battlestation id: 46 skap id: 3 tittel id: 34
    Battlestation id: 47 skap id: 3 tittel id: 35
    Battlestation id: 48 skap id: 5 tittel id: 35
    Battlestation id: 49 skap id: 3 tittel id: 36
    Battlestation id: 50 skap id: 3 tittel id: 37
    Battlestation id: 51 skap id: 3 tittel id: 38
    Battlestation id: 52 skap id: 4 tittel id: 38
    Battlestation id: 53 skap id: 3 tittel id: 39
    Battlestation id: 54 skap id: 3 tittel id: 40
    Battlestation id: 55 skap id: 3 tittel id: 41
    Battlestation id: 56 skap id: 4 tittel id: 42
    Battlestation id: 57 skap id: 4 tittel id: 43
    Battlestation id: 58 skap id: 4 tittel id: 44
    Battlestation id: 59 skap id: 5 tittel id: 45
    Battlestation id: 60 skap id: 5 tittel id: 46
    Battlestation id: 61 skap id: 5 tittel id: 47
    Battlestation id: 62 skap id: 5 tittel id: 48
    Battlestation id: 63 skap id: 5 tittel id: 49
    Battlestation id: 64 skap id: 5 tittel id: 50

    Amasing! Thanks.

  4. #4
    Admin
    Join Date
    Sep 2010
    Rep
    Posts
    3,404
    Country
    Norway
    You can also use mysql_fetch_array if you want to save the loop in the php script.
    I generally don't answer questions in PMs. Post it at the forum instead!

    His personality is so magnetic that he's unable to carry credit cards. He never say something taste like chicken... not even chicken. He's a lover, not a fighter, but he is also a fighter so don't get any ideas!

    Find out what you don't do well in life, and don't do that thing

  5. #5
    Senior Member
    Thread Starter

    Join Date
    Mar 2011
    Rep
    Posts
    154
    Country
    Norway
    Btw what would you say about the security in the script? Would it be smart to use it on etc public sites, or is it vulnerable?

    Hrhrhrhrhhr


    Obviously, design is not my job. :9

    Ojojoj, starting to love jQuery here!

    It works Question gets stored successfully in the database.

    kontakt.php
    PHP Code:
    <!doctype html>
    <
    html lang="no">
    <
    head>
        <
    meta charset="x-EBCDIC-DenmarkNorway">
        <
    title>JQuery Example</title>
    </
    head>
    <
    body>
        <
    h3>Send spørsmål til biblotekar</h3>
        
        <
    p>Navn: <input id="name" type="text" /></p>
        <
    p>Email: <input id="email" type="text" /> (Du vil bli svart på mailen)</p>
           <
    p>Spørsmål: <br><textarea id="question" cols="80" rows="10" type="text"></textarea></p>
        
        <
    p>
        <
    input id="save_button" type="button" value="Save" />
        <
    span id="save_status"></span>
        </
    p>
        
        <!-- 
    Loading javascripts -->
        <
    script type="text/javascript" src="motor/js/jquery.js"></script>
        <script type="text/javascript" src="motor/js/ajax.js"></script>
    </body>
    </html> 
    ajax.js
    Code javascript:
    $('#save_button').click(function() {
    // grab values
    var name = $('#name').val();
    var email = $('#email').val();
    var question = $('#question').val();
     
    // show loading text
    $('#save_status').text('Loading...');
     
    // perform http request
    $.post('motor/php/settings.php', {name: name, email: email, question: question}, function(data) {
    	$('#save_status').text(data);
    });
    })

    kontaktapi.php
    PHP Code:
    <?php
    header 
    ('content-type:text/html;charset=iso-8859-1');
    include 
    'DB.php';

    if (isset(
    $_POST['name'], $_POST['email'], $_POST['question'])) {
        
    $name mysql_real_escape_string(htmlentities($_POST['name']));
        
    $email mysql_real_escape_string(htmlentities($_POST['email']));
           
    $question mysql_real_escape_string(htmlentities($_POST['question']));
        
        
    $update mysql_query("INSERT INTO  `kontakt` (`navn` ,`epost` ,`melding`) VALUES ('$name',  '$email',  '$question')");
        if (
    $update === true) {
            echo 
    'Innlegg utført! Biblotekar vil svare deg på epost straks meldingen er lest.';
        } else if (
    $update === false) {
            echo 
    mysql_error();
        }
    }
    ?>
    DB.php
    PHP Code:
    <?php
    mysql_connect
    ('localhost''test''test');
    mysql_select_db('nith');
    ?>
    Gonna have to start to sniff around with simple register/login/restrict so you only can do these things when logged in thingy. Any recommended tutorial for this?
    Last edited by Brannfjell; 22-03-2012 at 00:59.

  6. #6
    Admin
    Join Date
    Sep 2010
    Rep
    Posts
    3,404
    Country
    Norway
    Use PDO, it's safe, and you don't need to rewrite the script to use another database format.

    Quote Originally Posted by Brannfjell View Post
    Gonna have to start to sniff around with simple register/login/restrict so you only can do these things when logged in thingy. Any recommended tutorial for this?
    Why do you need a tutorial? It's exactly the same as you did in the previous script, except you put "session_start()" after <?php, and set $_SESSION["loggedin"] = true and vertify it upon login vertification?
    I generally don't answer questions in PMs. Post it at the forum instead!

    His personality is so magnetic that he's unable to carry credit cards. He never say something taste like chicken... not even chicken. He's a lover, not a fighter, but he is also a fighter so don't get any ideas!

    Find out what you don't do well in life, and don't do that thing

  7. #7
    Senior Member
    Thread Starter

    Join Date
    Mar 2011
    Rep
    Posts
    154
    Country
    Norway
    Well, now I stumbled upon another problem:



    So yeah, I need to make a search function which will return multiple rows (data result from mysql query) in the red box displayed.

    Red box id is #results

    Here is what I have made so far, using previous sample scripts: (not sure if it works, my php knowledge is limited). I intend to read lots of tutorials once im done with the exam, dont got time for that now.

    api.php (sorry its mostly norwegian )
    PHP Code:
    <?php 
      $tableName 
    "battlestation";

      
    //--------------------------------------------------------------------------
      // 1) Connect to mysql database
      //--------------------------------------------------------------------------
      
    include 'db.php';
      
    $con mysql_connect($host,$user,$pass);
      
    $dbs mysql_select_db($databaseName$con);
      
      
    //--------------------------------------------------------------------------
      // 1.5) Fetch SHIT
      //--------------------------------------------------------------------------
      
      // Starten av SQL querien, vil bli bygd videre etter hva brukeren søker på
      
    $temp "select a.utgave, a.serie_id, b.forfatter_navn FROM nith.tegneserie a, nith.forfatter b where a.forfatter_id = b.forfatter_id ";

        
    // standard verdier som blir oppdatert hvis brukeren oppgir spesifikasjon i søkefeltet.
      
    $tittel "";
      
    $forfatter "";
      
    $utgave 0;
      
        
    // henter tittel/serie navn
      
    if (isset($_POST['comics_tittel'])) {
        
    $tittel mysql_real_escape_string(htmlentities($_POST['comics_tittel']));
      }
      
      
    // Hvis tittel er fylt ut, søk etter tittel i databasen
      
    if (strlen($tittel) > 1) {
        
    $temp $temp "AND a.utgave ='$tittel' ";
      }
      
      
    // Henter forfatternavn
      
    if (isset($_POST['comics_forfatter'])) {
        
    $forfatter mysql_real_escape_string(htmlentities($_POST['comics_forfatter']));
      }
      
      
    // Hvis forfatter er fylt ut, søk etter forfatter i databasen
      
    if (strlen($forfatter) > 1) {
        
    $temp $temp "AND b.forfatter_navn ='$forfatter' ";
      }
      
      
    // Henter utgave nummer
      
    if (isset($_POST['comics_utgave'])) {
        
    $utgave mysql_real_escape_string(htmlentities($_POST['comics_utgave']));
      }
      
      if (
    $utgave >= 1) {
        
    $temp $temp "AND a.serie_id ='$utgave' ";
      }
      
      
    $temp $temp "order by a.utgave";
      
      
      
    //--------------------------------------------------------------------------
      // 2) Query database for data
      //--------------------------------------------------------------------------
      
    $result mysql_query($temp);          //query
      
    $array = array();
      
    $row mysql_fetch_row($result);
      while(
    $row) {
        
    $array[] = $row;
        
    $row mysql_fetch_row($result);
      } 

      
    //--------------------------------------------------------------------------
      // 3) echo result as json 
      //--------------------------------------------------------------------------
      
    echo json_encode($array);

    ?>
    I am not sure how I shall make the ajax/javascript communicator between the php script and html code.

    the html code:
    HTML Code:
    <!-- Her starter den oransje COMICS seksjonen -->
    <div id="comics">
    	<div id="container">
    		<div id="comics_h1"><img src="bilder/comics.png" alt="overskriften comics"></div>
    		<div id="pil_1"><img src="bilder/pil.png" alt="pil 1"></div>
    		<div id="pil_2"><img src="bilder/pil.png" alt="pil 2"></div>
    		<div id="pil_3"><img src="bilder/pil.png" alt="pil 3"></div>
    		<div id="pil_4"><img src="bilder/pil.png" alt="pil 4"></div>
    		<div id="sokepil1"><img src="bilder/sokepil.png" alt="grafisk element"></div>
    		<div id="sokepil2"><img src="bilder/sokepil.png" alt="grafisk element"></div>
    		<div id="sokepil3"><img src="bilder/sokepil.png" alt="grafisk element"></div>
    		<div id="comic_text">LETER DU ETTER EN TEGNESERIE? <br>BRUK SØKEFUNKSJONEN UNDER!</div>
    		<!-- Her er de tre formene -->
    		<div id="comics_form">
    			<form method="post" action="??????">
    				<label></label>
    				<input id="comics_tittel" name="tittel" placeholder="Tittel:">
    						
    				<label></label>
    				<input id="comics_forfatter" name="forfatter" placeholder="Forfatter:">
    						
    				<label></label>
    				<input id="comics_utgave" name="utgave" placeholder="Utgave:">
    		
    				<input id="comic_submit" name="comic_submit" type="submit" value="submit">
    			</form>
    		</div>
    		<div id="resultat"></div>
    		</div>
    		<!-- Her slutter de tre formene -->
    	</div>
    </div>
    <!-- Her slutter den oransje COMICS seksjonen -->
    Last edited by Brannfjell; 27-03-2012 at 16:35.

  8. #8
    Admin
    Join Date
    Sep 2010
    Rep
    Posts
    3,404
    Country
    Norway
    It's a submit form, the easy way is just to skip the AJAX (is it a requirement) and just read the post fields directly and render the page again with the new data.

    If you want the jQuery ajax method, then read a tutorial: Submit A Form Without Page Refresh using jQuery | Nettuts+
    I generally don't answer questions in PMs. Post it at the forum instead!

    His personality is so magnetic that he's unable to carry credit cards. He never say something taste like chicken... not even chicken. He's a lover, not a fighter, but he is also a fighter so don't get any ideas!

    Find out what you don't do well in life, and don't do that thing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •