First time playing with SQLite, I've created a database and table and set the column id as the primary key unique.
I've inserted some data into the table and can see the data when I do :
SELECT * FROM members;
However when I run the following query I'm not getting the results I expected.
$result = $db->query("SELECT * FROM members WHERE plan = 'User' AND id = '$users_id'");
echo "<pre>";
print_r($result->fetchArray());
echo "</pre>";
I get:
Array
(
[0] => 124578986532-784512986452
[id] => 124578986532-784512986452
[1] => User
[plan] => User
[2] => 54890
[phone] => 54890
[3] => 698-78450
[staffID] => 698-78450
[4] => WestWing
[location] => WestWing
[5] => 1
[active] => 1
)
Which is the correct result, but why do I get duplicates for each returned entry ?
ie: Why [0] & [id], [1] & [plan] ??
As each users ID is unique searching for it will only ever return one result set, how do I use the results as variables I can use elsewhere within the page ?
eg: $id = $result['id'] ?
Thanks
fetcharray contains numerical array and associative array, so your result should be
For Named index array
$result = $db->query("SELECT * FROM members WHERE plan = 'User' AND id = '$users_id'");
echo "<pre>";
print_r($result->fetchArray(PDO::FETCH_ASSOC));
echo "</pre>";
Here the Crossponding Data
$result->fetchArray(PDO::FETCH_BOTH) -The rows are arrays with both numeric and named indexes
$result->fetchArray(PDO::FETCH_ASSOC) -The rows are arrays with named indexes.
$result->fetchArray(PDO::FETCH_NUM) - The rows are arrays with numeric indexes.
Related
This question already has answers here:
sql PDO fetchall duplicate object keys?
(2 answers)
Closed 2 years ago.
I have a mysql table that has the following fields
STUDENTID | FIRSTNAME | SURNAME | DOB | SCHOOLID
A form is used for a user to search for a student and output all those with matching first and surnames
The following SQL statement returns the PDO fine
$sqlstmnt2 = 'SELECT * FROM students WHERE firstName = :fname AND surname = :sname AND schoolID = :schoolID';
// prepare PDOstatement as $query ...
// ...
$query->execute();
$_SESSION['foundPupils'] = $query->fetchAll();
However, when I pass this through to another PHP page in a session variable, I'm confused as to how to access each field individually. I have the following code
foreach($_SESSION['foundPupils'][0] as $found){
echo($found);
}
This outputs the found data but the issue is that it outputs it twice, and it's just a long string of data which can't be formatted nicely. My questions are:
Why does each result output twice?
How do I access the individual fields within this array (kind of like foundPupils[0]['firstName'] for example?
According to the documentation, both the method PDOStatement::fetch and PDOStatement::fetchAll accepts a $fetch_style parameter. If not set, the default value is PDO::FETCH_BOTH. That means the fetched array will both reference the fields by position (e.g. 0, 1, 2) and by column name (e.g. "firstName", "surname").
So by default, your fetched results would be something like this:
Array
(
[0] => Array
(
[name] => apple
[0] => apple
[colour] => red
[1] => red
)
[1] => Array
(
[name] => pear
[0] => pear
[colour] => green
[1] => green
)
[2] => Array
(
[name] => watermelon
[0] => watermelon
[colour] => pink
[1] => pink
)
)
To fix this, you need to call your fetch function (I suppose it is PDOStatement::fetchAll) with PDO::FETCH_COLUMN as the fetch style:
$query->execute();
$_SESSION['foundPupils'] = $query->fetchAll(PDO::FETCH_COLUMN);
Query results are returned and stored in a result object. Therefore, you have to iterate through the result either using xxxx_fetch_array or xxxx_fetch_row. for example
$sql='SELECT * FROM table_name';
$result = mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
echo $row['COLUMN_NAME'].'<br />';
}
in my controller i have an associative array in the following pattern!
Array ( [0] => Array ( [id] => 13 ) [1] => Array ( [id] => 14 ) )
now what i want to do is there is some data on another table where these ids are referenced as foreign keys what i want to do is iterate through this array of ids and fetch data from another table on the basis of these ids!
this will be my query
$this->db->select("path");
$this->db->from('main_data');
$this->db->where("f_key",$id); //this is the id i want to take from array i written above
$query = $this->db->get();
return $query->result_array();
Does this give you enough to complete your work or do you need more? I can't test my code if I include your codeigniter code in there, since I don't have your database.
<pre>
<?php
$arrOfIds = array( array( "id" => 13 ), array( "id" => 14 ));
foreach($arrOfIds as $row) {
$id = $row["id"];
echo $id . "\r\n";
//remove the echo statement and run your queries and do whatever you need to do
}
?>
</pre>
Need to find if two arrays match, and then where they match pull data from the mysql row in which they match. Should I use
$sql = "SELECT * FROM around";
$resultsd = $conn->query($sql);
foreach($resultsd as $rowd) {}
if (array_intersect($ar1, $ar2)) {
$sword[] = $rowd['TIM'];
}
or should I use
if (in_array($ar1, $ar2)) {
$sword[] = $rowd['TIM'];
}
Getting the arrays like:
$ar1[] = $rowd['nim'];
$ar2[] = $rowd['nim'];
Then how does one go about pulling the specific row that they match at?
I am seeing that they match, and printing out the array's okay:
Array ( [0] => dcbabcbded ) Array ( [0] => fafeafaebee [1] => afabfdefcbb [2] => dcbabcbded
But when I trying a echo the mysql data where they match I fail:
Array ( )
i would go with sql IN clause.
You have an array of customer names: $a = array('john','rob','paul');
implode array $nms = join(',',$a);
Make sql: 'SELECT * FROM tabl WHERE name IN ('.$nms.')';
do the array intersection first (or what you just have to..) to have an array of needed names.
use $new = array_intersect(Array ( [0] => dcbabcbded ), Array ( [0] => fafeafaebee [1] => afabfdefcbb [2] => dcbabcbded)) : then make valid sql as stated in my answer above.
If u are sure you've allways have array intersenct with one or none values, then make sql just with first array element: $ar[0] using sql WHERE clause.
I have two PHP arrays. One contains a group name and another contains a pay wage value.
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 1 [3] => 3 );
This means there are four employees on the schedule. Two are assigned to group 1, another to group 4 and the last to group 3.
The second array is as follows:
$tot_wages_array = Array ( [0] => 500 [1] => 44 [2] => 80 [3] => 11.25 );
This is a sample array of each employee's wage. Both arrays are constructed in order as values are added in a mysql while loop as it pulls the info from the database.
Later on down the line, I combine the two arrays to get one array where the key is the group number and the value is the total wages for that group:
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
This works like a charm EXCEPT for when more than one employee is assigned to the same group. These arrays are built in a mysql while loop as it loops through each employee's info:
array_push($tot_wages_array, $totemp_wages_sch); // Add their wage to the array
array_push($group_wages_array, $emp_data['group_id']); // Add their group to the array
Instead of just pushing the data to the array, I need to do this... I know the english but I don't know how to code it:
If $emp_data['group_id'] exists as value in $group_wages_array, add nothing to this array but get the key. Add $totemp_wages_sch to $tot_wages_array where key = group_wages_array key
I know it sounds more like an SQL query but I have to keep the keys and values in order so that they can be combined later in the page. If I can get this to work right, The arrays shown in the example would be:
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 3 );
$tot_wages_array = Array ( [0] => 580 [1] => 44 [2] => 11.25 );
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
$combined_group_wages = Array ( [1] => 580 [4] => 44 [3] => 11.25 );
...I've got to make this work using PHP. Any ideas?
I came up with a solution based on a combination of two of the answers submitted below. Here it is if it can help someone:
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] += $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
array_push($tot_wages_array, $totemp_wages_sch);
}
This should do it:
$group_wages_array = array(1, 4, 1, 3);
$tot_wages_array = array(500, 44, 80, 11.25);
$combined_group_wages = array();
for ($i=0; $i<count($group_wages_array); $i++) {
$group = $group_wages_array[$i];
if (array_key_exists($group_wages_array[$group], $combined_group_wages)) {
$combined_group_wages[$group] += $tot_wages_array[$i];
} else {
$combined_group_wages[$group] = $tot_wages_array[$i];
}
}
print_r($combined_group_wages);
Yields:
Array
(
[1] => 580
[4] => 44
[3] => 11.25
)
But I recommend that you just switch to using objects to better represent your data.
If I could see the entirety of the code that would help a lot, but here's your English converted to php. Show me more code and I can perfect it, until then try this ->
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] = $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
}
I am trying to insert multiple rows in a MySQL table from PHP arrays. I managed with with help of other members to get set of values in a pair of brackets but when i try to insert this i get "Error: Column count doesn't match value count at row 1" I donot know where am i going wrong. my codes are as below: (The number of values i get vary according to user input)
$docno1=array();
$serialno = array();
$acc_name = array();
$debit = array();
$credit = array();
for ($i=1;$i<=$rowcount;$i++)
{
//echo 'Accountname'.$i.' :'.($_GET['accname'.$i]).'<br>';
$docno1 [] = ($_GET['docno']);
array_unshift($docno1,"");
unset($docno1[0]);
$serialno [] = $i;
array_unshift($serialno,"");
unset($serialno[0]);
$acc_name[] = ($_GET['accname'.$i]);
array_unshift($acc_name,"");
unset($acc_name[0]);
$debit[] = ($_GET['DrAmount'.$i]);
array_unshift($debit,"");
unset($debit[0]);
$credit[] = ($_GET['CrAmount'.$i]);
array_unshift($credit,"");
unset($credit[0]);
}
$sum_dr = array_sum ($debit);
$sum_cr = array_sum ($credit);
echo ' values of $multi<br>';
$multi = array(
($docno1),
($serialno), //Array for a row of fields
($acc_name),
($debit),
($credit),
($docno1)
);
print_r($multi);
$new = array();
foreach($multi as $key=>$value) {
$new[] = "'".implode("','", $value)."'";
}
echo '<br>Values of $new <br>';
print_r($new);
$query = "(".implode("), (",$new).")";
echo $query.'<br>';
mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());
echo "Inserted successfully";
die;
The results i get are :
values of $multi
Array
(
[0] => Array
(
[1] => 3434
[2] => 3434
)
[1] => Array
(
[1] => 1
[2] => 2
)
[2] => Array
(
[1] => Lemon
[2] => Kidney Beans
)
[3] => Array
(
[1] => 20
[2] => 10
)
[4] => Array
(
[1] => 0
[2] => 0
)
[5] => Array
(
[1] => 3434
[2] => 3434
)
)
Values of $new
Array
(
[0] => '3434','3434'
[1] => '1','2'
[2] => 'Lemon','Kidney Beans'
[3] => '20','10'
[4] => '0','0'
[5] => '3434','3434'
)
('3434','3434'), ('1','2'), ('Lemon','Kidney Beans'), ('20','10'), ('0','0'), ('3434','3434')
Error: Column count doesn't match value count at row 1
mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());
You are trying to insert something into 6 fields, so that $query string must have 6 values in it, or you get this error.
You have a lot of $query's that are 2 values. And that's not 6
It looks to me as if you are mapping your array the wrong way round. You're trying to add two records with six fields each, but what you're actually putting into the SQL statement are six records with two fields each.
This is why MySQL is complaining -- because you've told it you want to update six fields, but in each of the records you've given it, you've only specified two fields.
You need to build your array differently.
I assume that $docno1, $serialno, $acc_name, $debit and $credit will always all have the same number of array elements (it appears from your code that you are assuming this, so I'll follow you in your assumption).
In that case, you need to build your array something like this:
$multi = array();
foreach($docno1 as $key=>value) {
$multi[] = array(
$docno1[$key],
$serialno[$key], //Array for a row of fields
$acc_name[$key],
$debit[$key],
$credit[$key],
$docno1[$key])
}
Replace the block in your code where you set $multi with this, and your program should work.
Look at what print_r($multi) looks like now, and you'll see the difference.
(note, there are more efficient ways of writing your whole program than this, but I've focused on giving you a drop-in replacement for this specific bit, to help show you where you were going wrong, rather than simply rewriting the whole program for you)
Hope this helps.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the specific inserts -- for which you didn't specify a value.