Mysql result array search - php

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
}
}

Related

PDO Arrays are not structured as expected [duplicate]

I have a script that is outputting to a CSV file. However, even though there is currently one row in the database, the output I'm getting is echoing out each column from each row in the table twice.
For example:
1,1,John,John,Smith,Smith,2014,2014
Should be
1,John,Smith,2014
This worked fine before I went with PDO and prepared statements, so I'm thinking maybe I'm not understanding how fetch() works correctly.
Below is my code. Any idea what I could be doing wrong?
// get rows
$query_get_rows = "SELECT * FROM Contacts ORDER BY date_added DESC";
$result_get_rows = $conn->prepare($query_get_rows);
$result_get_rows->execute();
$num_get_rows = $result_get_rows->rowCount();
while ($rows_get_rows = $result_get_rows->fetch())
{
$csv .= '"'.join('","', str_replace('"', '""', $rows_get_rows))."\"\n";
}
echo $csv;
exit;
You should say to PDO, that you want only an associative array or a numbered array:
while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_ASSOC))
to get an associative array or
while ($rows_get_rows = $result_get_rows->fetch(PDO::FETCH_NUM))
to get an array indexed by the column number
from PDOStatement::fetch
fetch_style
Controls how the next row will be returned to the caller.
This value must be one of the PDO::FETCH_* constants, defaulting to
value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to
PDO::FETCH_BOTH).
PDO::FETCH_ASSOC: returns an array indexed by column name as returned
in your result set
PDO::FETCH_BOTH (default): returns an array indexed by both column
name and 0-indexed column number as returned in your result set

Mysql returns duplicate results with numbered key

I did a SELECT query on MySQL and get this as result.
The problem is how can I remove the 2nd duplicated results at for instance we use the 1st item in the list. "0":"1" is a duplicate for "id":"1" I would rather use "id" instead of "0" as the key later on the the app. How could I remove this to simplify the results. I do notice that the "0" means the 1st column as the successive columns does add up by 1.
Here's the $query I run.
SELECT id FROM clubsinformation WHERE :comparisonTime < updateTime
This is caused by most likely the fetching mode, you need to fetch it by associative indices only because right now you're including both associative and numeric index fetching:
No matter what DB API you got, MySQLi or PDO, just set it to associative.
So that it turn it doesn't include the numeric indices, only the column names as keys:
So this would roughly look like in code (from looking at your query placeholders, it seems PDO, so I'll draft a PDO example):
$data = array(); // container
$query = 'SELECT * FROM clubsinformation WHERE :comparisonTime < updateTime';
$select = $db->prepare($query);
$select->bindValue(':comparisonTime', $comparisonTime);
$select->execute();
while($row = $select->fetch(PDO::FETCH_ASSOC)) { // associative
$data[] = $row; // only includes column names
}
// then finally, encode
echo json_encode($data);
// OR SIMPLY
// $data = $select->fetchAll(PDO::FETCH_ASSOC); // associative
// echo json_encode($data);
That fetching is by way of PDO API. If you're using MySQLi you can still use the basic idea.

MySQL query returns two array items, why?

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..

mysql query to retrieve every single row of data

$q = "SELECT * FROM user";
$res = mysqli_query($conn, $q) or die(mysql_error());
$userList = "";
while($user = mysqli_fetch_array($res))
{
$userList .= $user['userList'].";;";
}
echo $userList;
I don't understand the while part:
Why assign the mysqli_fetch_array to $user using while?
How can the $user have index of userList?
Why concatenate with ;;?
To answer your questions:
i) mysqli_fetch_array() has two possible return values. It either returns an array of the current row that the database result set pointer points to, then advances the pointer to the next row, or it returns false if you have reached the end of the result set. The while() evaluates the value that is set to $row either continuing the loop if it is an array or stopping the loop if $row equals false
ii) The $user array has both numerical indexes for each field (i.e. 0,1,2,... [#fields - 1]) and associative indexes of the column names for the table (i.e. 'field1', 'field2', etc.). In this case one of the fields in the database is userList, so accessing $user['userList'] returns that column value for the row being worked with. BNote that the query itself would have beeter been written as SELECT userList FROM user since that is the only field you are interested in. There is no reason whatsoever to select and transfer all field data if you have no need for it. It is also rarely useful to use just mysqli_fetch_array(), as you rarely need both numerical and associative indexes on the record.It is usually best to specifically request ther associative or numerical array result depending on which you need.
iii) This code is simply building a string rather than an array of results which might be more common. For whatever reason the code writer decided values in the string should be separated by ;;.

Array not containing values when using "in_array" (php) w/ mysql_query

I continue to struggle with array! This is probably easy to answer.
I'm retrieving a data set from MYSQL w/ PHP. I get an array that has the 1st row (ala the mysql_fetch_array). Typically I would just loop through this and get each value, but in this case I'm already in the middle of a loop and I need to find out if a particular value exists in the full data set (which will be more than 1 row).
I figured I could just loop through and put all the values into an array with something like:
$query = "SELECT MapId FROM Map Where GameId = $gl_game_id";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
$map_set = array();
while($row = mysql_fetch_assoc($result_set)) {
$map_set[] = $row;
}
When I print_r this, I do in fact get the full data set (e.g. all rows of MapId from table Map).
So now, when I go to look in there and see if a value (that is coming out of this other loop) exists, it won't find it.
So my code looks like:
if (in_array($i, $map_set)) {
echo "yes, it's there baby!";
}
But it doesn't work. I tried hard coding the array, and that does in fact work. So there is simply something wrong with the way I'm constructing my array that this function doesn't like it.
if (in_array($i, array(40,12,53,65))) {
echo "yes, it's there baby!";
}
arrrg... I do hate being a noobie at this.
Function mysql_fetch_assoc returned array.
If you make print_r($map_set) then you will see that is 2-dimension array. Sure in_array not worked.
Just replace $map_set[] = $row; by $map_set[] = $row["MapId"]; and then try again.

Categories