I have this code
while($row = mysql_fetch_row($result))
{
echo '<tr>';
$pk = $row[0]['ARTICLE_NO'];
foreach($row as $key => $value)
{
echo '<td>' . $value . '</td>';
}
which gets pk. pk is then passed on to the axjax part with this:
function GetAuctionData(pk)
{
.....
var url="get_auction.php?"
url=url+"cmd=GetAuctionData&pk="+pk;
And finally used in a separate php file with:
$pk = $_GET["pk"];
$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
the second php file works fine when using it by itself and passing parameters. Likewise there are no errors anywhere. The problem seems to be with passing or generating $pk, as the links in the output file result in $pk being incremednted by 2, eg 4, 6, 8 etc
I can not understand why this is happening.
mysql_fetch_row link does not have subarrays. It will return the first field as 0, next as 1, etc.
Try with
$pk = $row[0];
This can easily be used with your foreach
while($row = mysql_fetch_assoc($result))
$pk = $row['ARTICLE_NO'];
or this gives you both associative and numbered array.
while($row = mysql_fetch_array($result, MYSQL_BOTH))
$pk = $row['ARTICLE_NO'];
EDIT:
Based on
$result = mysql_query("SELECT SELLER_ID, ACCESSSTARTS, ARTICLE_NAME FROM {$table}");
You have to include the row you want a value from. ;)
$result = mysql_query("ARTICLE_NO, SELECT SELLER_ID, ACCESSSTARTS, ARTICLE_NAME FROM {$table}");
BTW: Im pretty sure this nested loop will not produce what you want. You'll get 3 links to each article_no. The first with seller_id as text, the second text is accessstarts, and the last link with the same href will have the text article_name.
Maybe something like this?
while($row = mysql_fetch_assoc($result))
{
$pk = $row['ARTICLE_NO'];
echo '<td>' . $row['ARTICLE_NAME'] . '</td>';
}
As troelskn says, it looks like you are a bit confused as to what mysql_fetch_row is returning.
mysql_fetch_row will return $article[0], $article[1] etc
there are also:
mysql_fetch_assoc // return $article['ARTICLE_NO'], $article['otherfield'] etc
mysql_fetch_array // returns an array that is effectively the above two array_merge'd
mysql_fetch_object // returns a stdclass object, as if mysql_fetch_assoc had been passed to get_object_vars()
you need to refactor a bit, in light of this ....
I don't think this does what you expect:
$pk = $row[0]['ARTICLE_NO'];
Try with:
$pk = $row['ARTICLE_NO'];
The other responses here should answer your problem sufficiently, but I just wanted to add an extra debugging tip to could help you should you run into a similar problem in the future.
You can do some very basic debugging by merely printing to the screen information about the variables you're working with. (A PHP IDE will often have more powerful debugging features, but for something like this problem, this method will be fine)
Your original code:
while($row = mysql_fetch_row($result))
{
echo '<tr>';
$pk = $row[0]['ARTICLE_NO'];
foreach($row as $key => $value)
{
echo '<td>' . $value . '</td>';
}
}
You notice that the GetAuctionData function isn't getting its variable properly. Add this line:
$pk = $row[0]['ARTICLE_NO'];
var_dump($pk);
If you look at the output when you run the file, you'd probably see it saying that $pk is null. Hmmm, that didn't work. Let's change it a bit:
$pk = $row[0]['ARTICLE_NO'];
var_dump($row);
You'd now see something like this:
array(2) {
[0]=> string(2) "12"
[1]=> string(7) "myValue"
}
Aha! Now that you can see exactly what you're working with, you'd see that the code you wanted to use in the first place was:
$pk = $row[0];
var_dump() is your friend. If you're working with arrays, print_r() gives you similar information, but formatted nicely.
Good luck.
Related
$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.
it's just fetching the first element from the table.
Table name is categories which contains 2 columns : id, category
I cant understand why is it fetching just first row from the table.
<?php
$sql = "SELECT category FROM categories";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
//print_r($row);
?>
You need to iterate through the result set in order to retrieve all the rows.
while($row = mysql_fetch_assoc($result)) {
print($row);
}
Also, stop using mysql_ functions. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
Use this in while loop :
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Just like you wrote mysql_fetch_assoc($result); will get only one row. You have to use loop to get it all.
If you call mysql_fetch_assoc just once, you'll get only the first row...
while(false !== $row = mysql_fetch_assoc($result)) {
print_r($row)
}
The function you are using only does one record.
Try. ..while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['category'];
echo "";
}
For retrieve result set Use loop as per your need
foreach
Use when iterating through an array whose length is (or can be) unknown.
as
foreach($row as $val)
{
echo $val;
}
for
Use when iterating through an array whose length is set, or, when you need a counter.
for(i=0;i<sizeof($row);i++)
{
echo $row[$i];
}
while
Use when you're iterating through an array with the express purpose of finding, or triggering a certain flag.
while($row=mysqli_fetch_array($query))
{
echo $row['flag'];
}
I have a part of an application that loops through a return of a MySQL query (as we all know) in the form of an Array. However, I need several different format settings placed on some of the items returned, for example, one column needs Japanese currency, the other has American currency and one of the returned items is a link to an image.
I would use the names of the column, however this same function that I am using to accomplish this will be used for many different tables.
This is what I have for the loop so far.
while($row = mysql_fetch_array($result)) {
for($i=0;$i<=count($row);$i++) {
if($row[i]==$row['Yen_Price']) {// I didn't expect this to work...but this is what I would like to do.
echo "Hello";
}
echo "<td>" . $row[$i] . "</td>";
}
}
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $value) {
if ($key == 'Yen_Price') {
echo "Hello";
}
echo "<td>$value</td>";
}
}
Having said that, using the same function to process all results from all possible tables will soon be rather unmanageable. You should customized this to fit the occasion like so:
while ($row = mysql_fetch_assoc($result)) {
echo "<td>Foo: $row[foo]</td>";
echo "<td>Bar: $row[bar]</td>";
}
I'd markup these results specific to each table but if you want it to be ultimately flexible, try this smelly code
// using mysql_fetch_assoc() as we don't need the numeric indices
while($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
echo '<td>';
switch ($col) {
case 'US_Price' :
printf('$%0.2f USD', $val);
break;
case 'Yen_Price' :
printf('¥%0.2f', $val);
break;
case 'image' :
printf('<img src="%s">', htmlspecialchars($val));
break;
}
echo '</td>';
}
}
Note that this is a known antipattern and you should really think about another way to approach the problem.
Use the below code. You can modify it as you want.
$select=" WRITE YOUR SELECT QUERY HERE ";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
// YOU CAN USE HERE FOR EACH LOOP AS PER YOUR REQUIREMENTS.
Thanks
Before I became a framework fanatic I used to have a bit different approach. My db library had set of methods that returned me array of record sets. This way I keep my db interaction totally separate from how I consume the record sets. Having done this, its easy to set up a grid template which can look at array and then act accordingly. Here is some pseudo code
$recordSets = $db->returnRecordSets("select some, columns from tablename");//extra param if I need array to be associative
$recordSetsCount = count($recordSets);
if($recordSetsCount == 0){ echo 'Nothing to be done!'; //exit or return or break here}
for($i=0; $i< $recordSetsCount; $i++ == 0){
$recordSet = $recordSets[$i];
/*Inspect the $recordSet array and use it*/
}
I need to have a single row of data "printed out" through php.
So, take this example from w3schools:
http://www.w3schools.com/PHP/php_mysql_select.asp
There is a cicle that goes through all the rows ( in this case, 2) and prints them out. The end result is:
Peter Griffin
Glenn Quagmire
What I want is to be able to select row 1 or 2 (or more) and just have that row of data selected. Then I could say something like (I know this doesent work, just an example):
echo $row["Name",2];
And get:
Glenn Quagmire
I believe I have to get a special parameter in mysql_fetch_array, but I cant find it anywhere, and I bet its something really simple. Please help me out, full examples/tutorials/guides links are preferred.
you have 2 options. First is edit your SQL query like exmaple below this will return just 2nd row from database.
$result = mysql_query("SELECT * FROM Persons" WHERE id = 2);
Or during the foreach loop fetch all result into another array.
$result = mysql_query("SELECT * FROM Persons");
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row['FirstName'] . " " . $row['LastName'];
}
As far as i know mysql doesnt have a function to return the entire query as an array.
So you can switch to using PDO (recommended):
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll();
echo $result[1]['name'];
or if you must use the mysql_functions just create an array with the loop:
while($row = mysql_fetch_array($result)) {
$result[] = $row;
}
echo $result[1]['name'];
fetchall the results into an array and print the row you want.
I have the below code. It is only returning the first charater of a string.
$conn = Mage::getSingleton('core/resource')->getConnection('connection_write');
$str = 'something to search for';
$fields = 'content_field1, content_field2, content_field3, content_field4';
$idFields = 'id_field1, id_field2, id_field3, id_field4';
$tables = 'table1, table2, table3, table4';
$table = explode(', ', $tables);
$field = explode(', ', $fields);
$rowId = explode(', ', $idFields);
$i=1;
while ($i<4) {
$f = $field[$i];
$id = $rowId[$i];
$sql = $conn->select()->from($table[$i], array($f, $id))->where($f . " LIKE ?", '%' . $str . '%');
$result = $conn->fetchRow($sql);
foreach ($result as $row) {
var_dump($row[$id]);
}
$i++;
}
However, if I use var_dump($row); the entire string from both the id fields and the content fields are outputted.
Can anyone explain to me what I am doing wrong?
Thanks in advance.
However, if I use var_dump($row); the entire string from both the id fields and the content fields are outputted.
well, why do you use var_dump($row[$id]); which exactly equals to "take $id'th char from $row string" then?
foreach ($result as $row) {
$result is a list of rows you selected from the table. Each $row is a string.
$row[$id] simply selects the $id'th character from this row string.
I believe the problem has to do with the fact that $result is an array (possibly an associative array) of strings. (I'm not familiar with Mage, but I'm assuming that fetchRow() returns only a single row and not all of your rows.)
Therefore, what's happening is you've probably got something like this:
$result = array("tom","dick","harry");
When you run foreach($result as $row), $row looks like "tom", "dick", and "harry" on each iteration.
Because $row is a string, calling $row[$id] makes PHP attempt to get get a single character from the $row string. Because it's expecting $id to be an integer in this case, it's probably interpreting "id_field1" as 0, which will end up returning the first character of your string.
I'm not exactly sure what you're trying to get back, but most likely this can be solved by changing your foreach section to be something like...
foreach ($result as $resultColumn) {
var_dump($resultColumn);
}
->fetch() is not needed when fetching data by using foreach statement like in your code (Please see examples below). If you use ->fetch() unnecessarily, this situation often occurs (I experienced this too..)
foreach statement and while statement have the following relationship. Please consider rewriting the code, referring to this:
<?php
$stmt = $pdo->query('SELECT * FROM Entry');
while ($row = $stmt->fetch()) {
echo $row['title'], $row['content'];
}
//this while statement above is equivalent to the foreach statement below
foreach ($stmt as $row) {
//->fetch() is not needed for foreach statement!
echo $row['title'], $row['content'];
}