Results 1 to 3 of 3

Thread: Collating all results

  1. #1
    Join Date
    Mar 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Collating all results

    Hi,

    I've been learning PHP/MySQL over the past few weeks from a book.
    I've now created sql database and some php scripts that can retrieve, add and delete content from all the different tables within them.

    One of the tables has one field named 'answers', this a VARCHAR(200) and contains strings of text/numbers.

    What I want to be able to do is query the entire table into one array, then use the shuffle() function to randomly select one answer.

    Here's my code so far (appears after a radio button form):
    if (isset($_POST['q1']))
    {$selected = $_POST['q1'];

    $query = "SELECT * FROM m$selected";
    $result = mysql_query($query);
    if (!$result) die ("Database access failed: " . mysql_error());

    $test=mysql_fetch_field($result);

    print_r ($test);
    }


    Surely print_r($test); should display an array of all the entries from the table?

    This is what i get from the FETCH:
    "Warning: mysql_fetch_field(): supplied argument is not a valid MySQL result resource"

  2. #2
    Join Date
    Sep 2008
    Location
    Bristol - UK
    Posts
    842
    Thanks
    32
    Thanked 132 Times in 131 Posts

    Default

    The query itself is invalid "m$selected" is the problem, also you are using "mysql_fetch_field" which will get information about the current field, but I don't think that's what you want.

    This is what I think you're after:

    PHP Code:
    <?php

    if (isset($_POST['q1'])) {
     
    $selected $_POST['q1'];

        
    $query "SELECT * FROM `{$selected}`";
        
    // As long as $selected is a valid fieldname

        
    $result mysql_query($query);
        if(!
    $result)
         die(
    mysql_error());

        else {
         while(
    $data mysql_fetch_array($result)) {
            echo 
    $data['FIELDNAME_HERE'] . '<br />';
         }
        }
    }
    ?>
    Should work.

  3. #3
    Join Date
    Mar 2010
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Ahh, I see. Thanks Schmoopy!

    I found another way too using the rand() function which eliminates the need for the shuffle() function;

    if (isset($_POST['q1']))
    {$selected = $_POST['q1'];

    $query = "SELECT * FROM $selected";
    $result = mysql_query($query);
    if (!$result) die ("Database access failed: " . mysql_error());

    $row = mysql_num_rows($result);
    $rowa =$row - 1;

    $rows = mysql_result($result,rand(0,$rowaa));

    print_r ($rows);
    }


    Can't believe how much there is to learn to writing websites!
    Thanks for you help

Bookmarks

Posting Permissions

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