I am connecting to my SQL server getting information from it using the following code:
if ($_POST['searchdb']) {
$searchi="".$_POST['search'];
$query = "SELECT * FROM consume WHERE type LIKE '%{$searchi}%' OR description LIKE '%{$searchi}%'";
if($result= mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
print_r($row);
}
}
}
I have each value stored only once in my database but I get the following output:
Array
(
[0] => RF Connector
[Type] => RF Connector
[1] => Male N Type Angle Cable Mtg.
[Description] => Male N Type Angle Cable Mtg.
[2] => Carousel
[Location] => Carousel
[3] => 2
[Drawer] => 2
[4] => Test
[Supplier] => Test
[5] => 12345678
[Order Code] => 12345678
[6] => 1
[id] => 1
)
Why does the data seem to appear twice? Or is this normal?
This is normal behaviour, see here http://php.net/manual/en/mysqli-result.fetch-array.php
If you want numeric indices use this
mysqli_fetch_array($result,MYSQLI_NUM);
and for associative indices use this
mysqli_fetch_array($result,MYSQLI_ASSOC);
If you don't pass any parameter you will get an array containing both.
Because you're using mysqli_fetch_array which puts two copies of the data into the result, once using the column number (starting from the left most column, numbered as 0) and once using the column's name.
You might find using mysqli_fetch_assoc instead of mysqli_fetch_array to be more useful, you get one copy of the data and you get useful column names.
this is because you used while mysqli_fetch_array($result)
^^^^^
it will give you both object and associative
use while mysqli_fetch_assoc($result)
you will get associative values
Yes, it is normal when using mysqli_fetch_array
Replace it with mysqli_fetch_assoc and you will get associative array which contains data only once or use mysqli_fetch_row to get enumerated array which also contains data only once.
source:
http://php.net/manual/en/function.mysql-fetch-assoc.php
http://php.net/manual/en/function.mysql-fetch-row.php
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 />';
}
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.
Apologies is advance as I am very much a PHP amateur...
I currently have the following code that extracts all of the values from an SQL table field.
$unit_data = mysql_query("SELECT `value1` FROM `unit_stats`");
$unit_info = array();
while($row = mysql_fetch_assoc($unit_data)) {
$unit_info[] = $row['value1'];
}
print_r($unit_info);
The array uses standard indexing ([0], [1] etc) so my output is:
Array ( [0] => 40 [1] => 30 [2] => 70 ...)
However I need to use another field within the same SQL table as my Index rather than the standard numerical method. E.g.
Array ( [item1] => 40 [item2] => 30 [item3] => 70 ... )
Can anyone advise a solution?
Regards,
Dan
Assuming that you are selecting the other field in your select statement, you could simply define the key as below.
while($row = mysql_fetch_assoc($unit_data)) {
$unit_info[$row['index_value_from_sql']] = $row['value1'];
}
Arrays in php can be used as maps that associates one value (index) to the other (value). Index does not need to be the default numeric values. You can define them according to your liking. Hope this helps.
I am pulling some data from a mysql table via the following:
$result = mysql_query("SELECT characters_ID, name, borndate, deathdate, marrieddate, ispregnant FROM characters WHERE isfemale='1'",$db);
$femaledata = array();
while ($row_user = mysql_fetch_assoc($result))
$femaledata[] = $row_user;
This gives me an array that looks like this:
Array (
[0] => Array ( [characters_ID] => 2 [name] => Helene [borndate] => 35 [deathdate] => 431 [marrieddate] => 157 [ispregnant] => 0 )
[1] => Array ( [characters_ID] => 4 [name] => Isabelle [borndate] => 161 [deathdate] => [marrieddate] => 303 [ispregnant] => 1 )
[2] => Array ( [characters_ID] => 7 [name] => Helene [borndate] => 326 [deathdate] => [marrieddate] => [ispregnant] => 0 )
[3] => Array ( [characters_ID] => 72 [name] => Faylinn [borndate] => 335 [deathdate] => [marrieddate] => [ispregnant] => 0 )
[4] => Array ( [characters_ID] => 74 [name] => Relina [borndate] => 349 [deathdate] => [marrieddate] => [ispregnant] => 0 )
)
Now I need to remove any characters who have a value for deathdate or ispregnant, and then I need to run some code on the others. For instance I need to grab the borndate value, compare it to the current date to find age, and based partly on age, I need to run code for each to determine if the character has become pregnant on the turn.
Apologies that this seems like a long-reaching question. Multidimensional arrays still seem to confound me.
Edit: (question needs to be more clear)
Can you please suggest the best way that I would either explode or break up the array, and then do conditional modification to the data, or instead how I could remove unneeded data and then do conditional modification to the data.
My ultimate output here would be taking suitable female characters (not dead or pregnant already), and based on their age, giving them a chance at becoming pregnant. If true, I'd throw some code back at the SQL database to update that character.
Thanks!
All the things you need could probably get done with SQL :
Now I need to remove any characters who have a value for deathdate or
ispregnant
Simply add some argument to your WHERE condition :
isPregnant IS NULL AND deathdate IS NULL
For instance I need to grab the borndate value, compare it to the
current date to find age
Depending of your field format the maths could be done in SQL , have look to the DATE function of mysql
Don't underestimate the power of your sql server , 99% of the time it is probably faster than php to work on data set.
Instead if immediately removing some rows from your array, try limiting the data you recieve through SQL.
You can loop through your array like this:
foreach($femaledata as $female)
{
echo $female['name'];
}
do you mean something like this?
$femaledata = array();
while ($row_user = mysql_fetch_assoc($result)) {
$ok = false;
// do you validation for every user
if($ok) array_push($femaledata,$row_user);
}
TJHeuvel gave you the right answer, and you should accept that answer. However, to inform: multidimensional arrays need not confound. Let me see if I can explain.
In PHP, you can put any object at all into an array, including other arrays. So, let's say you have an array that contains other arrays. When you iterate over that array using a looping construct (usually a foreach loop), each iteration of the loop will give you another array; if you want to access the elements of this sub-array, just loop over it. This is called a nested loop. Example:
$r = array(
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
foreach ($r as $cur) {
foreach ($cur as $num) {
echo $num;
}
}
In each iteration of the outer loop, $cur contains an array; the inner loop iterates over contents of this array. This technique allows you to process arrays of any dimension.
However, in your specific case, you don't need to use an inner loop to iterate over your subarrays. You only need to access certain elements of your subarrays by their keys, rather that processing all of them in turn. So, a simple foreach loop will do.
For some reason my array I am returning is not what I expect. Could someone explain to me why I am getting the current results, and what I can do to fix it? Here is the code in question:
public static function getProduct($_row, $_value)
{
$stmt = _DB::init()->prepare("SELECT pid, name, quantity, price, cost
FROM products
WHERE $_row = ?"
);
if($stmt->execute(array($_value)))
{
while ($row = $stmt->fetch())
return $row;
}
}
$product = Class::getProduct('pid',1);
print_r($product);
When I print the following array I am getting two results per row like so:
Array ( [pid] => 1 [0] => 1 [name] => Boondoggle [1] => Boondoggle [quantity] => 12 [2] => 12 [price] => 9.9900 [3] => 9.9900 [cost] => 12.9900 [4] => 12.9900 ) Boondoggle
I was only wanting to show the associative results. What is wrong with my function?
From the looks of it you are using PDO to communicate with your DBMS. The PDOStatement::fetch() method's first argument is a parameter to tell it what to return. By default it returns each column in both name format and numbered index format to allow iterating through columns easier. To just get the column names as indexes, you can pass it PDO::FETCH_ASSOC to your call. So the fetch statement would look like this:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)
See here for more details:
http://www.php.net/manual/en/pdostatement.fetch.php
Pass PDO::FETCH_ASSOC to your fetch call:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
edit: I'm just assuming you're using PDO, of course