This question already has answers here:
MySQLi query returns only one row
(3 answers)
Closed 6 years ago.
Here, I want to print those value which are in table.
So, my query is like this:
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
$roleres = mysqli_query($conn,$get_role_query);
$r_id = mysqli_fetch_assoc($roleres);
Here, 333 is not in table but 1 and 2 are in table.
When I am printing this like,
print_r($r_id);
It only gives me 1 but not getting 2 which is also in table. I don't want 333 that is fine. But I am getting only 1, not getting 2.
UPDATED BELOW:
As you all suggest to use while loop, I did like this:
$r_role = mysqli_num_rows($roleres);
for($i=0;$i<=$r_role;$i++)
{
print_r($r_id);
}
But I am getting output like this:
Array
(
[id] => 1
)
Array
(
[id] => 1
)
Array
(
[id] => 1
)
From above query, I just want output like,
Array
(
[0] => 1
[1] => 2
)
Any suggestion would be appreciated.
Thanks.
Use while in order to fetch multiple values from the table:
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
$roleres = mysqli_query($conn,$get_role_query);
while($r_id = mysqli_fetch_assoc($roleres))
{
echo $r_id['id'];
}
You can also use an object method instead array method.
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
if ($result = $mysqli->query($get_role_query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
echo $obj->id;
}
}
/* free result set */
$result->close();
You are not using mysqli_fetch_assoc() correctly. It fetches one record at a time. Use it as follows:
while($r_id = mysqli_fetch_assoc($roleres))
{
print_r($r_id);
}
Related
I m trying to pass comma separated values inside IN condition in cakephp 3 but it gets values with single quotes inside brackets ('12,18').
Please suggest me how to remove this.
Expected output (12,18)
Below is my code
public function checkPermission(){
$userId = $this->request->getSession()->read('Auth.User.id');
$arodta = TableRegistry::get('Aros');
$Arosdata = $arodta->find()->where(['foreign_key' => $userId])->first()->toArray();
if(!empty($Arosdata)){
$aroId = $Arosdata['parent_id'];
$aroAcodata = TableRegistry::get('ArosAcos');
$arocodata = $aroAcodata->find()->where(['aro_id =' => $aroId]);
if(!empty($arocodata)) {
foreach ($arocodata as $data){
$acoId[] = $data['aco_id'];
}
if(!empty($acoId)){
$acoData = implode(',',$acoId);
$acosName = TableRegistry::get('Acos');
$arac = $acosName->find()->where(['id IN' => $acoData]);
sql($arac);exit;
}
}
}
}
My Array data
$acoId[] =
Array
(
[0] => 12
[1] => 18
)
I am getting output like
SELECT
Acos.id AS `Acos__id`,
Acos.parent_id AS `Acos__parent_id`,
Acos.model AS `Acos__model`,
Acos.foreign_key AS `Acos__foreign_key`,
Acos.alias AS `Acos__alias`,
Acos.lft AS `Acos__lft`,
Acos.rght AS `Acos__rght`
FROM
acos Acos
WHERE
id in ('12,18')
In Cakephp you can directly pass array for IN clause instead imploding it with comma. Use $acoId array in your query:
$arac = $acosName->find()->where(['id IN' => $acoId]);
I'm trying to save with foreach
here is what i get from my form
Array
(
[mulai] => 2016-08-28
[akhir] => 2016-08-31
[keterangan] => remarks
[nip] => Array
(
[0] => 1004384
[1] => 1602744
[2] => 1501039
)
)
and then here is my saving query.
$jumlahrange = $this->db->query("SELECT DATEDIFF(day,'".$mulai."','".$akhir."') AS diff")->row();
$totaldata = count($nip);
$skrg = $this->db->query("SELECT GETDATE() tgl")->row();
for($x = 0;$x<=$totaldata;$x++)
{
for($y=0;$y<$jumlahrange->diff;$y++){
$this->db->query("INSERT INTO attendance
(Nip,AttendanceDate,InTime,OutTime,AttendanceCode,RosterCode,LocationCode,Remarks,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy)
values(
'".$nip[$x]."',DATEADD(DAY,".$y.",'".$mulai."'),'','','P3','','','".$keterangan."','".$skrg->tgl."','$niplogin','','')
");
}
}
i have no problem with my save but i have empty field like this in my table. In row 10,11,12 . That row should not exist right?.
I using SqlServer 2008 and Codeigniter . I know i can use insert_batch, but i want use this way.
in your line for($x = 0;$x<=$totaldata;$x++) i'm pretty sure you wanted to write < instead of <=
To overcome these kind of issues you can use foreach loop instead
foreach($resourcedata as $value){
//your code goes here and you will get all array elements sequentially in **$value** variable
}
This one is right at your fingertips. $nip[$x] is null. Error log or dump and die on the first loop $nip[$x] and see what it returns. If it is in fact not null, then it might be a data type problem (string vs int).
I am trying to create an array from an mysql query,
It gets around 300 values from the database yet only the first value is stored in the array. when I echo the array it says: Array ( [0] => 0.99 ). What I'm trying to archieve is
Array ( [0] => 0.99 )
Array ( [1] => 0.25 )
etc.
$activering = mysql_query("SELECT tarieven.id, bundels.bundel_id, betaalmethodes.bet_id , bundels.psp_id, bundels.aanmeldkosten, bundels.maandelijkse_kosten, bundels.transactiekosten, bundels.batchkosten, psp.psp_naam, tarieven.percentage, tarieven.prijs, bundels.actief
FROM tarieven
INNER JOIN bundels
ON tarieven.bundel_id = bundels.bundel_id
INNER JOIN betaalmethodes
ON tarieven.bet_id = betaalmethodes.bet_id
INNER JOIN psp
ON bundels.psp_id = psp.psp_id");
if($activering === FALSE) { die(mysql_error()); } // to do better error handling
if ($result = mysql_fetch_array($activering)) {
$prijs = array($result['prijs']); }
It's probably something really easy but I just don't see it..
Try
while ($result = mysql_fetch_array($activering)) {
$prijs[] = array($result['prijs']);
}
your over writing the value(array) in hte loop so you only get the last one:
$prijs[] =$result['prijs']; }
I have three arrays that look like this:
ingredientQTY is the first input box in each row, measurements is the select/dropdown in each row, and ingredientsNAME is the last input box in each row. As you can see, there can be infinite numbers of ingredientQTY's, ingredientNAME's, and measurements.
When I send them to my php script, the data is in arrays like:
IngredientQTY
(
[0] => 5 //The first row
[1] => 5 //The next rows value
)
Measurements
(
[0] => Bunch //The first row
[1] => Bunch //The next rows value
)
IngredientName
(
[0] => 5 //The first row
[1] => 5 //The next rows value
)
I'm trying to upload them to a table called ingredients that has 3 columns: ingredientNAME, ingredientQTY, and measurements.
In my php script, I'm combining them into a multidimensional array, which is assigned to $ingredientsROW:
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
$ingredientQTY = $this->input->post('ingredientQTY');
$measurements = $this->input->post('measurements');
$ingredientNAME = $this->input->post('ingredientNAME');
$ingredientsROW[] = array($ingredientQTY, $measurements, $ingredientNAME);
break;
}
My question is: How can I get group all the first row of form elements (which means the first ingredientQTY, the first measurements dropdown and the first ingredientNAME and insert them into a row?
The only way I could think of is to have one insert where I insert ingredientQTY, then look up the id of the row I just inserted and use two mysql updates to enter for the same row, but I'm pretty sure there is more efficient ways of going about this.
Would something like this work?
foreach($_POST['IngredientQTY'] as $index=>$qty)
mysql_query("insert into ingredients ".
"set IngredientQTY='".addslashes($qty)."'".
", measurements ='".addslashes($_POST['measurements'][$index])."'".
", ingredientNAME ='".addslashes($_POST['ingredientNAME'][$index])."');
Iterate through the data and create an array like this:
for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
$rows[] = array(
'QTY' => $ingredientQTY[$i],
'measurement' => $measurements[$i],
'name' => $ingredientNAME[$i]
);
}
With this array you can create the insert quite easily and insert whole rows.
Please, see Cha's answer where we are pretty close the final solution. We are debugging the code with these data
database in PostgreSQL
test sql-queries
--
Problem related to the Unsolved problem in the code
How can you refer to the php -element in the following array?
I have the following data
Array
(
[1] => Array
(
[tag] => Array
(
[0] => php
[1] => scripts
)
)
[2] => Array
(
[tag] => Array
(
[0] => ssh
[1] => network
)
)
)
where the arrays stand for tags_and_id, question_id and tag respectively.
In other words, the variable $tags_and_id has the column question_id and that still has a subcolumn tag and that still each single tag.
I would like know how you can refer to the tag php.
I run unsuccessfully getting nothing as an output
echo $tags_and_id[1]['tag'][0];
If you want to add more information about each question, you can simply add to $end_array[1].
This is the array my first foreach statement creates:
// The end result turns out to be something like this:
array(
1 => array(
'tags' => array(
0 => "php",
1 => "sql"),
)
);
<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=noa user=noa password=123");
if( empty($_GET) ) {
// to get titles and question_ids
$result_titles_tags = pg_prepare( $dbconn, "query777",
"SELECT question_id, title
FROM questions
WHERE question_id IN
(
SELECT question_id
FROM questions
ORDER BY was_sent_at_time
DESC LIMIT 50
)
ORDER BY was_sent_at_time
DESC LIMIT 50;"
);
$result_titles = pg_execute( $dbconn, "query777", array());
// TAGS
$result_tags = pg_prepare( $dbconn, "query9",
"SELECT question_id, tag
FROM tags
WHERE question_id IN
( SELECT question_id
FROM questions
ORDER BY was_sent_at_time
DESC LIMIT 50
);"
);
$result_tags = pg_execute( $dbconn, "query9", array());
and the code in the question initially
// Go through each Tag
while( $tags_and_Qid = pg_fetch_array( $result_tags )) {
// Add the Tag to an array of tags for that question
$end_array [ $tags_and_Qid['question_id'] ] ['tag'] [] = $tags_and_Qid['tag'];
}
// First compile the Data
// Go through each question
while( $titles_and_Qid = pg_fetch_array( $result_titles ) ) {
echo ("<div class='question_summary'>"
. $titles_and_Qid['title']
// Problem here!
// How can you print the titles such that
// they are assigned to each tag -set?
);
$i = 0;
// Then Loop Through each question
foreach( $end_array as $tags_and_Qid['question_id'] => $tags_and_Qid['tag'] )
{
echo ("\n\nITERATION NUMBER IS " . $i); // The code is buggy here
// For instance, we get 9 iterations for 3 questions
// Create the starting HTML
echo ("<div class='tags'>");
// Go through each tag
// not sure about this
foreach( $end_array[$tags_and_Qid['question_id']] ['tag'] as $tag )
{
echo ( "<a class='post_tag' href='?tag="
. $tag
. "'>"
. $tag
. "</a>"
);
}
// end the html
echo '</div>';
$i++;
}
echo ("</div>");
}
// to end the list of questions
echo ("</div>"
);
}
?>
If print_r is failing, then something is wrong before that. Your data is probably not being structured in the way you think it is being structured.
And can I just recommend that if you only have the tag and the question name, you just store as a single level array that looks like the following:
array(
'php' => '7',
'sql' => '7',
'python' => '3'
)
If you have other things you're going to store then yeah, you'll have to do what you're doing. In that case, if you can't access the array with the keys in brackets, then your keys are probably not what you think they are, or there is something wrong with your code somewhere.
I looked at your code, and why are you accessing query results like $row[0], instead of $row['question_id'] ?
Also, you can't print_r($result_tags) , because data from a query is not actually stored by PHP, it is only referenced. therefore you have to use a while loop to go through it, as the script will call one row of results at a time.
You say: foreach( $result_tags as $question_id => $data ) This doesn't make sense, because there is no value for $result_tags except for a reference to the query that can be used to call one row of results at a time. Instead you want to do:
while( $row2 = pg_fetch_array( $result_tags )) {
$question_id = $row2['questions_question_id'];
$data = $row2['data'];
$end_array[$question_id]['tags'][] = $data;
// you can't have your $data['tag'] as that refers to the
// value of an array that doesn't exist
}