Jump to content

Recommended Posts

Hello,

 

I was wondering if there is a way to create queries dynamically with php functions?

 

For example every time i want to display something from the db I do this:

$q = "SELECT id,something FROM table_name";
$r = $mysqli->query($q);
while ($row = $r->fetch_object())  {

echo $row->id;
echo $row->something;

}

 

So is there a way where I can use php function and so that all i have to do is type field names and table name and the rest is plug and play. I want to be able to reuse that function to. Is it possible? Not only is it possible but is it a right thing to do?

Link to comment
https://forums.phpfreaks.com/topic/172670-solved-creating-queries-dynamically/
Share on other sites

Hi

 

Possible and quite easy.

 

Eg, build an array of the fields you want, and pass that.

 

<?php
$ArrayOfFields = array('id','name','address');

sqlFunction($ArrayOfFields);

function sqlFunction($PassedFields)
{
$q = "SELECT ".implode(',',$PassedFields)." FROM table_name";
$r = $mysqli->query($q);
while ($row = $r->fetch_assoc())  
{
	foreach($PassedFields AS $aField)
	{
		echo $row[$aField];
	}
}
}
?>

 

All the best

 

Keith

Keith,

 

Thank you very much.

 

now I noticed that you did fetch_assoc() why that instead of fetch_object()?

 

With this function I can put it in a function.php and include anywhere on the site right? just call that function like you have it on top of the function.

Hi

 

I used fetch_assoc as I am using normal mysql rather than mysqli most of the time, and with it returning a associative array it is easy to use the passed column names to get the values.

 

You will want to pass in the connection to the function (either as a parameter or as a global).

 

You can put it anywhere in your code, but think an included function needs to be included before it is used.

 

All the best

 

Keith

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.