Some useful php code

TFlan

I could change this in my User CP.
Reaction score
64
I was trying to find a nicer, easier way to extract data out of a mysql database, and this is what i came up with.

PHP:
function query($q){
	$result = mysql_query($q);
	if($result!=false){
		$results[0] = $result;
		$results[1] = mysql_num_rows($results[0]);
		$results[2] = mysql_num_fields($results[0]);
		for($i=0;$i<$results[1];$i++){
			for($f=0;$f<$results[2];$f++){
				$field = mysql_field_name($results[0], $f);
				$a = $i + 3;
				$results[$a][$field] = mysql_result($results[0], $i, $field);
			}
		}
		return $results;
	}else{
		return false;
	}
}

Here is how you would call it:
PHP:
$result = query(<mysql query here>);

Here is what it will come out as:
Code:
Array
(
    [0] => Resource id ##
    [1] => # of rows
    [2] => # of fields
    [3] => Array
        (
            [Field Name 1] => Row 1, Field 1 Value
            [Field Name 2] => Row 1, Field 2 Value
        )
    [4] => Array
        (
            [Field Name 1] => Row 2, Field 1 Value
            [Field Name 2] => Row 2, Field 2 Value
        )
)

Personally i thought it saved space, made mysql querys easier for me, and just looks better altogether.

Of course you can still do other things with that,

$result[0] = mysql_query(q);

So you can still do it the old fashion way: mysql_result($result[0], 0, 'blah');

Only thing u have to change from now on is the for() statements to get all the data.

So this is how all the for statements will have to be:
PHP:
$results = query(<mysql query here>);
for($o=0;$o<$results[1];$o++){
	$i = $o + 3;
	$field1 = $results[$i]['field1_name'];
}
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
If you want to extract the data from a table, you can use a dedicated syntax:
Code:
SELECT ... INTO OUTFILE
 

TFlan

I could change this in my User CP.
Reaction score
64
I think you misunderstood me.

Not extract into an external file, but make the data go into a nice little array that is easy to call upon.
 

enouwee

Non ex transverso sed deorsum
Reaction score
240
Not extract into an external file, but make the data go into a nice little array that is easy to call upon.

Doesn't mysql_fetch_assoc() do exactly the same as your code fragment:

Code:
for($f=0;$f<$results[2];$f++){
  $field = mysql_field_name($results[0], $f);
  $a = $i + 3;
  $results[$a][$field] = mysql_result($results[0], $i, $field);
}
 

TFlan

I could change this in my User CP.
Reaction score
64
didn't even know that was a function.

oh well :p
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top