I have a getData() function, and a database with two tables: employers and members.
I would like to pass a variable containing the table name, so inside an "if" I could execute the appropriate SELECT statement. My problem I believe that after the "if" the $stmt->bind_param(); doesn't know which $stmt to bind the take.
Any ideas on how I could achieve this?
Thanks
public function getData($table)
{
if ($table == "employers")
{
$stmt = $this->link->prepare("SELECT * FROM employers ");
}
else
{
$stmt = $this->link->prepare("SELECT * FROM members ");
}
$stmt->bind_param();
if ($stmt->execute())
{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
No, since you aren't binding anything, that ->bind_param method is superfluous. Just take that off.
public function getData($table)
{
$dataArray = array();
$t = ($table === 'employers') ? 'employers' : 'members';
$query = "SELECT * FROM $t";
$stmt = $this->link->prepare($query);
if($stmt->execute()) {
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$row = array_map('stripslashes', $row);
$dataArray[] = $row;
}
}
return $dataArray;
}
Sample Usage:
$data = $aministrator_query->getData('members');
$tbody = '';
foreach($data as $row) {
$tbody .= "<tr><td>{$row['user_id']}</td><td>{$row['user_password']}</td><td>{$row['user_first_name']}</td><td>{$row['user_last_name']}</td></tr>";
}
$table = sprintf('<table><thead><tr><th>ID</th><th>Password</th><th>First Name</th><th>Last Name</th></tr></thead><tbody>%s</tbody></table>', $tbody);
echo $table;
Related
I am fetching data from MYSQL database and Looping through the result but its returning only one row !!! can any one explain what's wrong
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
return $row;
}
}
}
The return should be outside the while loop !
Here is how you can get all the rows :
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
$arr = array();
while($row = $stmt->fetch_row())
{
$arr[] = $row;
}
return $arr;
}
}
Or you can do something like this return a generator and loop through :
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
see the result here !
echo '<pre>';
foreach (getAll() as $value) {
print_r($value);
}
Once you hit a return statement all execution of that function stops. You cannot return multiple times.
You can either return an array of all rows:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0) {
while($row = $stmt->fetch_row())
{
$array[] = $row;
}
return $array;
}
}
Or use it as a generator (probably not what you want):
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
I cannot get the
$result = DatabaseHandler::query($query);
while ($row = $result->fetch_assoc()) {
$this->mTaskDateCreated[] = $row;
}
to output the time once the user has submitted the form. I'm not sure whereabouts exactly the problems lies as the other two $result work as they return the text entered into the field.
How can I get the $result to return the value of the datetime?
<?php
class ProjectBody {
public $mTasks = array();
public $mTaskName = array();
public $mTaskDateCreated = array();
public function __construct() {
if(isset($_POST['task_name']) && isset($_POST['task'])) {
$task_name = DatabaseHandler::escape($_POST['task_name']);
$task = DatabaseHandler::escape($_POST['task']);
$query = "INSERT INTO `project` (name, task, date_created) VALUES ('$task_name', '$task', NOW())";
$result = DatabaseHandler::query($query);
}
$query = "SELECT * FROM `project` ORDER BY `id` DESC";
$result = DatabaseHandler::query($query);
while ($row = $result->fetch_assoc()) {
$this->mTaskName[] = $row;
}
$result = DatabaseHandler::query($query);
while ($row = $result->fetch_assoc()){
$this->mTasks[] = $row;
}
$result = DatabaseHandler::query($query);
while ($row = $result->fetch_assoc()) {
$this->mTaskDateCreated[] = $row;
}
}
}
?>
Thanks.
How do I fetch data from db using select query in a function?
Example
function ec_select_query($student, $row = '', $fields=array()) {
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
while($row = mysql_fetch_assoc($qry)){}
return $row;
}
If you want to return all rows then first save it in an array in while loop then return this array.
function ec_select_query($student,$row='',$fields=array())
{
$qry = "SELECT * FROM student";
$qry = mysql_query($qry);
$result = array();
while($row = mysql_fetch_assoc($qry))
{
$result[] = $row;
}
return $result;
}
Its is running code. Modify it according to your needs
$con = mysql_connect('localhost','root','') or die("Unable to connect to MySQL");
mysql_select_db('demo', $con) or die("Database not found");
function ec_select_query($student)
{
$query = "SELECT * FROM $student";
$result = mysql_query($query);
$row = array();
$getData = array();
while($row = mysql_fetch_array($result))
{
$getData[]=$row;
}
return $getData;
}
$information = ec_select_query('accountplans');
echo "<pre>"; print_r($information); die;
Try it
function select_query($table, $where=array(),$fields=array()){
$select_fields = $table."*";
if(!empty($fields) && is_array($fields)){
$select_fields = implode(",", $fields);
}
$sql = "select ".$select_fields." from ".$table." where 1=1 ";
if(!empty($where) && is_array($where)){
foreach ($where as $key => $value) {
$sql .= " AND ".$value;
}
}
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_assoc($result)){
$result[] = $row;
}
return $result;
}
Call Function
$fields = array("id","name","city");
$where = array('name = "abc"','city like "aaa"');
$students = select_query("studendts", $where, $fields);
This code might help you :
function ec_select_query($student,$row='',$fields=array())
{
$q = "SELECT * FROM student";
$q = mysql_query($qry);
while($row = mysql_fetch_array($qry))
{
return $row;
}
}
It is easiest way to produce entire data in array
function db_set_recordset($sql) {
$qry = mysql_query($sql);
$row= array();
while($out = mysql_fetch_assoc($qry)) {
$row[] = $out;
}
return $row;
}
$qry = "SELECT * FROM student";
$result = db_set_recordset($qry);
I am trying to return all the productnames from my MySQL table. At the moment this only returns the first name in the column
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
while($row = $stmt->fetch())
{
return $row['productname'];
}
}
How do I get it to loop through and select all the productnames?
One way you could do is just select only the productname column, and then use $stmt->fetchAll(PDO::FETCH_ASSOC).
public function selectAll ()
{
$stmt = Database::get()->query('SELECT `productname` FROM retrofootball_products');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
do:
public function selectAll () {
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
$allCols = array();
while($row = $stmt->fetch()) {
$allCols[] = $row['productname'];
}
return $allCols;
}
You are directly returning first value that was causing the problem.
Store each record in array and return that array.
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
while($row = $stmt->fetch())
{
$arr[] = $row['productname'];
}
return $arr;
}
You can just avoid looping through as you're using PDO and use fetchAll.
public function selectAll ()
{
$stmt = Database::get()->query('SELECT * FROM retrofootball_products');
return $stmt->fetchAll();
}
http://php.net/manual/en/pdostatement.fetchall.php
While I'm new to stmp too, I imagine this might work
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
// do something with $row
}
I want to return a set of values from function till the point they exist....
for example....
function abc($i="3"){
for($a=1;$a<=$i;$a++) {
$name='t'.$i;
$$name = "ae".$a;
}
//now i am returning values
return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
//but i only want to return $t1,$t2,$t3 depending on $i
}
Thanks....
#therefromhere
I am also creating an array in the loop , I'll paste the original code so that you can understand it in a better way
function extracting_comments($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
echo $params[0];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$i=0;
while($stmt->fetch()) {
$i++;
$name='t'.$i;
$$name = array();
foreach ($row as $b=>$elem) {
$atul[$b]=$row[$b];
}
$$name=$atul;
}
return array($t1,$t2,$t3,$t4,$t5,$t6,$t7,$t8,$t9,$t10);
$stmt->close();
}
}
now their are only 5 rows of data so their is no point returning $t6,$t7,$t8,$t9,$t10
and i want to fix it ,and i am calling the function using
$extract=extracting_comments($table, $fields,$condition,$order,$limit);
please help...thanks
Just build the array in your for loop:
function abc($i=3) {
$array = array();
for ($a=1; $a<=$i; $a++) {
$array[] = "ae".$a;
}
return $array;
}
After you edited your question an revealed us your actual problem, see here my proposal:
function extracting_comments($table, $fields, $condition, $order, $limit) {
$retVal = array();
$query = "SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if ($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
call_user_func_array(array($stmt, 'bind_result'), $row);
while ($stmt->fetch()) {
$retVal[] = $row;
}
$stmt->close();
return $retVal;
}
}
I believe this will help you. You have very complicated code with a lot of side effects and bug, you'd better to consider to redisgn it. Also putting statements after return will no have any effect, since it wouldn't be invoked.
function extracting_comments($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE ".$condition."
ORDER BY ".$order."
LIMIT ".$limit." ";
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
echo $params[0];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$i=0;
$result = array();
while($stmt->fetch()) {
$i++;
foreach ($row as $b=>$elem) {
$atul[$b]=$row[$b];
}
$result[]=$atul;
}
$stmt->close();
return $result;
}
}
It'd be cleaner to build the array as you go along, then you wouldn't need the temporary variables:
function abc($i="3") {
$myArray = array();
for($a=1;$a<=$i;$a++) {
$myArray[] = "ae" . $a; // add new values to the end of the array
}
return $myArray;
}
If you want to check if the variables exist (and are not null), use isset().