MySQL query returns two array items, why? - php

I'm running this query, on two tables, and in first table, table tblhosting two condition must be met, WHERE tblhosting.server = tblservers.id AND tblhosting.domain = 'provided domain'. "provided domain is unique and here is complete query:
$result = mysql_query("SELECT hostname FROM tblhosting, tblservers WHERE tblhosting.server = tblservers.id AND tblhosting.domain = 'developer.infonet.hr'");
Query return correct result set, but two times, here is also var_dump output:
array(2) {
[0]=>
string(18) "lin-b15.infonet.hr"
["hostname"]=>
string(18) "lin-b15.infonet.hr"
}
Why is returning two same results, correct output is one, because domain is unique, is this because result is generate with mysq_fetch_array, so it is returning both associative array, and normal indexed array?

use
mysql_fetch_row() to Get a result row as an enumerated array
or
mysql_fetch_assoc() to Fetch a result row as an associative array
For Multiple record use it in while condition..

Related

Results from firebird DB columns are nameless just numbers

I'm using the following code to query my Firebird database, but the results do not include the column names, just numbers. It's my first time working with Firebird, I only worked with MySQL. Is there a way to get column names instead of numbers?
$dbh = ibase_connect($cdb, $this->session->userdata('client_username'), $this->session->userdata('client_password'), 'utf-8', '100');
$rid = ibase_query($dbh, $query);
$coln = ibase_num_fields($rid);
$dataArr = array();
while ($row = ibase_fetch_row ($rid)) {
$dataArr[] = $row;
}
Result:
Array
(
[0] => Array
(
[0] => 1
)
)
How can I get the column name that was [User_Id] instead of [0]? Is it possible?
As suggested by Dharman in the comments, you need to use ibase_fetch_assoc instead of ibase_fetch_row to get a result using column names (associative array).
As documented for ibase_fetch_assoc:
fetches one row of data from the result. If two or more columns of the
result have the same field names, the last column will take
precedence. To access the other column(s) of the same name, you either
need to access the result with numeric indices by using
ibase_fetch_row() or use alias names in your query.
Compared to ibase_fetch_row:
Returns an array that corresponds to the fetched row, or false if
there are no more rows. Each result column is stored in an array
offset, starting at offset 0.
When you prepare a query Firebird returns the resultset information for it, including column datatypes and aliases. Use fbird_field_info(...) to query the alias.
https://www.php.net/manual/en/function.ibase-prepare.php
https://www.php.net/manual/en/function.ibase-field-info.php

MySQL Query, get a column value by a list of rowid's, including duplicate results in result

//List of id's I want displayname for
$IDListSQL = '10,10,10,11,10,10';
//My query statement
$q = "SELECT displayname FROM accounts WHERE id IN($IDListSQL)";
//Executes query
$Res = $DB->Query($q);
//Gets all results
$Rows = $Res->fetch_all();
echo var_dump($Rows);
//Output
#->array(2)
{
[0]=> array(1)
{
[0]=> string(14) "Apple"
}
[1]=> array(1)
{
[0]=> string(10) "Orange"
}
}
The behaviour I want is an array with all the displayname's in the $IDListSQL, even if its the same ID. I also want them in the order I specified. Trying to figure this out in 1 query rather than doing up to 16 separate select queries for the purpose this is for. Any help would be appreciated kindly.
I ended up getting this done with PHP since I already had an array of ID's in the specified order. Used my same query to only get one of each ID, then joined the data into my array with the help of a couple for loops. Appreciate the help, Ctznkane525 I think what you posted would work. It sounds like it is doing the same thing I done up in PHP, trying not to use complex queries unless absolutely necessary. Speed and high ccu is critical for this app.

PDO Statement does not return full array

I cant figure out why i only get 1 entry in the returning array, when the table has 4 entries in total.
My PDO code is:
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
$katarray=$stmtkat->fetch(PDO::FETCH_ASSOC);
var_dump($katarray);
The return array i get:
array(2) { ["id"]=> string(1) "1" ["kategorie"]=> string(12) "Coaching" }
The table has 4 rows, why do i get only the first row into the array?
What i am doing wrong? Obviously i am new to PDO.
Ty for your time.
You are only fetching one of the result rows produced by your query
If you use ->fetch() to get result rows one at a time you do it in a while loop like this
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
while ( $katarray=$stmtkat->fetch(PDO::FETCH_ASSOC) ) {
var_dump($katarray);
}
Or use fetchAll() to return all rows into a local array from a single call to the PDO Stmt object
$stmtkat = $this->db->prepare("SELECT * FROM kategorie");
$stmtkat->execute();
$katarray=$stmtkat->fetchAll(PDO::FETCH_ASSOC) ) {
var_dump($katarray);
You get only one row in return because:
PDOStatement::fetch — Fetches the next row from a result set
Use fetchAll() instead to get full array() of result or use fetch() inside while() loop.
Example with fetch() and while():
while ($stmtkat->fetch(PDO::FETCH_ASSOC)) {
var_dump($katarray);
}
Example with fetchAll():
$result = $stmtkat->fetchAll(PDO::FETCH_ASSOC)
var_dup($result);

Mysql result array search

I'm getting this column in this bd
$result = mysql_query("SELECT short FROM textos");
and I'm trying to echo only one of the results based on the array it returns:
$col = mysql_fetch_assoc($result);
echo "<b>Short:</b>".$col[1]."<br/>";
apparently this $col array can't be accessed this way. How should it be done? Thanks
That has been already stated in comments above, so just a bit of explanation here.
mysql_fetch_assoc retrieves a result row for you presented as an associative array (an array where keys are field names and values are field values). Your query returns only one field (which is short), but still it doesn't make your row a single scalar value - it remains an array, only with a single element.
So you need to refer it as $row['short'], or in your sample $col['short'].
Bear in mind that query might return no results - you can learn that by checking if the returned value is not an array but scalar false instead, e.g.
if ($col === false) {
echo 'Error occured<br/>';
} else {
echo "<b>Short:</b>".$col['short']."<br/>";
}
Putting LIMIT into your query like again comments suggest is a good idea as well because you wouldn't be returning potentially huge amount of data when you only need one row actually. The result would still come as a multi-dimensional array though, so that part won't change.
To access the first element use $col[0]['short'].
If you only want to output one element anyways you can add LIMIT 1 to the MySQL query.
After querying you should check if the result array is set otherwise php will throw an error saying that $col[0]['short'] is not set.
There are three mysql_fetch functions which getting rows:
mysql_fetch_array() Fetch an array with both indexes (numeric and associative)
mysql_fetch_num() Fetch an array with numeric indexes
mysql_fetch_assoc() Fetch an array with associative indexes
In your example you will get an array that is looking like this one for the function mysql_fetch_array():
array(2) {
[0]=>
string(3) "foo"
["short"]=>
string(3) "foo"
}
$statement = 'SELECT short FROM textos';
$result = mysql_result($statement);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
var_dump($row); // or echo "<b>Short:</b>".$row['short']."<br/>"; or something else you like to do with rows of the above statement
}
}

mysql query looped with results stored in an array

I have a shipping module I'm working to wrap up and am trying to query a mysql table, count the number of rows for a given line item on a PO, and store that result in an array. I don't think I can do group by within mysql as it will not provide a result for a line item that hasn't had any shipments against it. The intent is to take the original order quantity, count the number of units shipped against that via my query, and then subtract the units shipped from the original amount providing the remaining units to be shipped against that line item.
To ensure I receive even the zero qty for line items without shipments and to store that in the array I am trying to loop my query and store each single result as a value within my array. I'm open to suggestions on changing the approach if there is a better way.
Here is what I have for my query:
// I have a previous query that provides the number of line items for a given po. that number is stored in variable $num1
$a=1;
$LiShipped = array();
while($a<$num1){
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$LiShipped[] = mysql_fetch_array($query2);
$a++;
}
Unfortunately when I go to iterate through my array it appears as though nothing is stored in the array.
<?php
echo $LiShipped[0]; //results nothing
echo var_dump($LiShipped); // results array(1) { [0]=> NULL } array(2) { [0]=> NULL [1]=> NULL } array(3) { [0]=> NULL [1]=> NULL [2]=> NULL }
?>
Looks like all null values.
You need to execute the query (by calling mysql_query()) before you try and attempt to retrieve the result:
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$query2 = mysql_query( $query_2); // <-- NEED THIS
$LiShipped[] = mysql_fetch_array( $query2);
Note the above omits basic error checking and sanitation of the SQL query to prevent SQL injection.
You are not executing your query, it can't work. Try this code:
// I have a previous query that provides the number of line items for a given po. that number is stored in variable $num1
$a=1;
$LiShipped = array();
while($a<$num1){
$query2="SELECT count(E3_SN) AS SCount FROM Shipped WHERE Cust_Ord_Num = '$SO_Num' AND LineItem=$a";
$res = mysql_query($query2);
while($LiShipped[] = mysql_fetch_array($res));
$a++;
}

Categories