MYSQL - Select specific value from a fetched array

后端 未结 9 1396
青春惊慌失措
青春惊慌失措 2021-01-06 01:45

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.

相关标签:
9条回答
  • 2021-01-06 02:18

    This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.

    0 讨论(0)
  • 2021-01-06 02:35

    Yes, ideally you have to write another sql query to filter your results. If you had :

    SELECT * FROM Employes
    

    then you can filter it with :

    SELECT * FROM Employes WHERE Name="Paul";
    

    if you want every names that start with a P, you can achieve this with :

    SELECT * FROM Employes WHERE Name LIKE "P%";
    

    The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.

    0 讨论(0)
  • 2021-01-06 02:40

    If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:

    $row = array();
    
    while( $row[] = mysql_fetch_array( $result ) );
    

    Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].

    0 讨论(0)
  • 2021-01-06 02:42
    $result = mysql_query("SELECT * FROM ... WHERE 1=1");
    while($row = mysql_fetch_array($result)){
    /*This will loop arround all the Table*/
        if($row['id'] == 2){
        /*You can filtere here*/
        }
    
        echo $row['id']. " - ". $row['name'];
        echo "<br />";
    }
    
    0 讨论(0)
  • 2021-01-06 02:42

    Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:

    $count = 0;
    while($row = mysql_fetch_array($result)){
        if(++$count == 2)
        {
            //do stuff
        }
    }
    
    0 讨论(0)
  • 2021-01-06 02:42

    If you always want the second row, no matter how many rows you have in the database you should modify your query thus:

    SELECT * FROM theTable LIMIT 1, 1;
    

    See: http://dev.mysql.com/doc/refman/5.5/en/select.html

    0 讨论(0)
提交回复
热议问题