I have this piece of code from which i wish to get a single array that contains all value.
$sql = "SELECT * FROM interest where interest='".$interest."' and userid!='".$myuserid."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$userid = $row["userid"];
if($searchtype == 'both')
{
$sql2 = "SELECT * FROM register where id='".$userid."' and discover = 'on' and id!='".$myuserid."'";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2) > 0)
{
while($row2 = mysqli_fetch_assoc($result2))
{
echo "<pre>";
print_r($row2);
echo "</pre>";
}
}
}
}
}
The o/p that i am getting is something like this
Array
(
[id] => 1
[email] => A1
[username] =>B1
[password] => C1
[gender] => C1
)
Array
(
[id] => 2
[email] => A2
[username] => B2
[password] => C2
[gender] => D2
)
Array
(
[id] => 3
[email] => A3
[username] => B3
[password] => C3
[gender] => D3
)
But i wish to get this all data in a single array like this
Array
(
[0] => Array
(
[id] => 1
[email] => A1
[username] =>B1
[password] => C1
[gender] => C1
)
[1] => Array
(
[id] => 2
[email] => A2
[username] => B2
[password] => C2
[gender] => D2
)
[2] => Array
(
[id] => 3
[email] => A3
[username] => B3
[password] => C3
[gender] => D3
)
}
can anyone tell how i can do so
Create an array variable like $a=array(); at the start of your code
Get row value in array $a[]=your row value(while loop), then print this outside loop you will get all value in single array print like
print_r($a);
Take one array variable before while loop started like $user_data = array(); and in inner loop you have to set $user_data[] = $row2;
if (mysqli_num_rows($result) > 0) {
$user_data = array();
while($row = mysqli_fetch_assoc($result)) {
$userid = $row["userid"];
if($searchtype == 'both') {
$sql2 = "SELECT * FROM register where id='".$userid."' and discover = 'on' and id!='".$myuserid."'";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2) > 0) {
while($row2 = mysqli_fetch_assoc($result2)) {
$user_data[] = $row2;
}
}
}
}
print_r($user_data); //Print here your user_data outside the loop.
}
You are almost near to your goal, you just need to define one array and save each row's data in it
// array which contains all rows data
$all_rows = array(); // <------ step 1
if(mysqli_num_rows($result2))
{
while($row2 = mysqli_fetch_assoc($result2))
{
// every record data is stored here
$all_rows[] = $row2; // <------ step 2
}
}
if(!empty($all_rows))
{
print_r($all_rows);
}else
{
echo "do some thing else since zero records fetched";
}
Related
I try to execute multiple queries in one php file.
The first query works fine, but the second en third one return an empty array.
$DB_con = new PDO($dsn, $DB_user, $DB_pass, array(
PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION
));
$sql_sel_sponsoring = $DB_con->prepare('CALL SP_SELECT_SPONSORING(:id)');
$sql_sel_sponsoring->execute(array(':id' => $sponsor));
$sql_res_sponsoring = $sql_sel_sponsoring->fetchAll();
$sql_sel_sponsoring_type = $DB_con->prepare('CALL SP_SELECT_SPONSORING_TYPE()');
$sql_sel_sponsoring_type->execute();
$sql_res_sponsoring_type = $sql_sel_sponsoring_type->fetchAll();
$sql_sel_cbo_members = $DB_con->prepare('CALL SP_SELECT_CBO_MEMBERS()');
$sql_sel_cbo_members->execute();
$sql_res_cbo_members = $sql_sel_cbo_members->fetchAll();
With a vardump() I have different objects
var_dump($sql_sel_sponsoring);
var_dump($sql_sel_sponsoring_type);
var_dump($sql_sel_cbo_members);
Results
object(PDOStatement)#6 (1) { ["queryString"]=> string(30) "CALL SP_SELECT_SPONSORING(:id)" }
object(PDOStatement)#7 (1) { ["queryString"]=> string(32) "CALL SP_SELECT_SPONSORING_TYPE()" }
object(PDOStatement)#8 (1) { ["queryString"]=> string(28) "CALL SP_SELECT_CBO_MEMBERS()" }
But 2 of the 3 resultsets are empty
print_r($sql_res_sponsoring);
print_r($sql_res_sponsoring_type);
print_r($sql_res_cbo_members);
Giving:
Array ( [0] => Array ( [SID_SPONSORING] => 70 [0] => 70 [SID_SPONSOR] => 88 [1] => 88 [Jaar] => 2014 [2] => 2014 [Bedrag] => 60.00 [3] => 60.00 [Omschrijving] => Publiciteitsboekje heel A5 [4] => Publiciteitsboekje heel A5 ) )
Array ( )
Array ( )
How can I make it work?
how can i get the first row of result? Below is my code which is giving me an error like this Undefined index: module
if ( substr( $action, 0, 4 ) === "stl_" )
{
$query = "SELECT * FROM a_actions LEFT JOIN a_modules ON ( a_modules.id=a_actions.module_id )
WHERE a_actions.id=(SELECT dependency FROM a_actions WHERE action='{$action}') AND a_modules.module_status = 1 ";
$action = \Yii::$app->db->createCommand( $query )
->queryAll();
//print_r($action);die();
$module = $action[ 'module' ];
$action = $action[ 'action' ];
}
$action has value
Array ( [0] => Array ( [id] => 7 [module_id] => 7 [action] => index [label] => Members [dependency] => [created_by] => [created_at] => [updated_by] => [updated_at] => [is_deleted] => 0 [module] => members [module_name] => [module_status] => 1 ) )
in Yii1 i would have used
$action = \Yii::$app->db->createCommand( $query )
->queryRow();
You can use queryOne()
\Yii::$app->db->createCommand( $query )
->queryOne();
QueryOne()
I have a multidimensional array like this:
TAB = Array (
[field1] => Array ( [0] => 111 [1] => 777 [2] => 222 ... )
[field2] => Array ( [0] => MAT [1] => MAT [2] => MAT ... )
[field3] => Array ( [0] => 8A [1] => 8B [2] => 8C ... )
)
I want INSERT the values of this Array to the mysql temporary TABLE1, with PDO.
How can I to do?
Thanks.
ASSUMING PHP and ASSUMING you have a TABLE1 which has two location columns and one value column (one column for the location in the first array, the second for the location in the second array and the value column for the actual value).
$dbh is your database handler.
$keys = array_keys($TAB); // because the array is associative, we need array_keys
for ($i = 0; $i < $TAB.length; $i++){
for ($j = 0; $j < $TAB[keys[$i]].length; $j++){
$stmt = $dbh->prepare("INSERT INTO TABLE1 (location1, location2, value) VALUES (:location1, :location2, :value )");
$stmt->bindParam(':location1', $i);
$stmt->bindParam(':location2', $j);
$stmt->bindParam(':value', $TAB[$keys[$i]][$j]);
$stmt->execute();
}
}
Now I have 3 row of data.
id name date
1 data1 12-06-2013
2 data2 12-06-2013
3 data3 16-06-2013
now I want to group the 3 rows of data into a new array, something like:
Array
(
[2013-06-12] => Array
(
[0] => data1
[1] => data2
)
[2013-06-16] => Array
(
[0] => data3
)
)
the question is 1st i using foreach to show all date out.
<?php foreach($datax as $data):
echo $data['Model_Name']['id'];
endforeach;?>
then, while i looping i want to group up the $data sort to date as the multidimensional array as above.
Try below method,. you can add an additional column for date
$a = array(
array('datax' => array('id' => 1, 'name' => 'data1')),
array('datax' => array('id' => 2, 'name' => 'data2')),
array('datax' => array('id' => 3, 'name' => 'data3'))
);
$result = Set::classicExtract($a, '{n}.datax.id');
/* $result now looks like:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
*/
$result = Set::classicExtract($a, '{n}.datax.name');
/* $result now looks like:
Array
(
[0] => data1
[1] => data2
[2] => data3
)
*/
I am trying to run a db query in drupal where, the content type has a node association field, and I am trying to get all notes of that type, where the NID of the current node matches any of the nodes specified in said note association field.
a visual example
Nodetype1
-- Node Association Field
NodeType2
I would like to get all Nodetype1's where Node Association Field matches the NID of Nodetype2 that is currently loaded.
My current db query is like so:
db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);
and this returns nothing, when i know for a fact that such a node exists, I also tried dropping the WHERE statement and it returns an array like this:
DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql Object ( [shutdownRegistered:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array ( ) [driverClasses:protected] => Array ( [SelectQuery] => SelectQuery [DatabaseSchema] => DatabaseSchema_mysql [MergeQuery] => MergeQuery [DatabaseTransaction] => DatabaseTransaction [UpdateQuery] => UpdateQuery [InsertQuery] => InsertQuery_mysql ) [statementClass:protected] => DatabaseStatementBase [transactionSupport:protected] => 1 [transactionalDDLSupport:protected] => [temporaryNameIndex:protected] => 0 [connectionOptions:protected] => Array ( [database] => cityhound_dev [username] => blahblah [password] => blahblah [host] => localhost [port] => [driver] => mysql [prefix] => Array ( [default] => ) ) [schema:protected] => DatabaseSchema_mysql Object ( [connection:protected] => DatabaseConnection_mysql Object *RECURSION* [placeholder:protected] => 0 [defaultSchema:protected] => public [uniqueIdentifier:protected] => 4fd7fba9e563e2.50177866 ) [prefixes:protected] => Array ( [default] => ) [prefixSearch:protected] => Array ( [0] => { [1] => } ) [prefixReplace:protected] => Array ( [0] => [1] => ) ) [queryString] => SELECT * FROM field_data_field_promo_profile )
Any one have some ideas ?
db_query() returns an iterable object, so you just need to iterate over it:
$result = db_query("SELECT * FROM field_data_field_promo_profile WHERE field_promo_profile_nid=".$N->nid);
foreach ($result as $row) {
$entity_id = $row->entity_id;
// etc...
}
You should use parameters in your queries to prevent SQL injections.
For instance the query above should look like this:
$result = db_query("SELECT * FROM {field_data_field_promo_profile} p
WHERE p.field_promo_profile_nid = :nid ", array(':nid' => $N->nid);
foreach ( $result as $row ) {
$entity_id = $row->entity_id;
// etc...
}