Hello i'm going to check duplicated data from selected data but my code is not working properly
the my code is:
$cs="0";
$location=array();
$check=array(); $check[0]="";
while ($db_field = mysql_fetch_array($result)) {
for ($z=0; $z<=$cs;$z++){
if($check[$z]==$db_field['location']) {
//*in here going to check same or not
}
else {
//*if not same $location_c[$cs] will get
$location_c[$cs]= $db_field['location'];
$check[$cs]= $db_field['location'];
}
}
$cs++;
}
this code prints all data not checking duplicated data.
I think you should use in_array() to avoid duplication, I've also removed unnecessary things :
$location=array();
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['location'], $location_c)) {
$location_c[] = $db_field['location'];
}
}
assuming the duplicate is the location field
$cs="0";
$location=array();
$check=array();
while ($db_field = mysql_fetch_array($result)) {
for ($z=0; $z<=$cs;$z++){
if (in_array($db_field['location'], $check)) continue;
$check[]=$db_field['location'];
$location_c[$cs]= $db_field['location'];
}
$cs++;
}
but can't you avoid duplicates with your SQL query?
The first issue you have is in your for statement: for ($z=0; $z<=$cs;$z++). There is no need for this. You should use in_array() in order to determine, if what your looking for has been set. Also, there is no need to use incremental values for your key. If you use [] there is no overhead, and will automatically use number keys.
Lastly, it appears that there is no reason to use a $check array at all. You can go straight to $location_c. This cuts down a lot of code:
$location_c = array();
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['location'],$location_c)){
$location_c[]= $db_field['location'];
}
}
Related
I loop trough the rows with this code:
while ($row = $result->fetch_assoc()) {
//...
}
But how is it possible before the mysqli_fetch_assoc to check if there will be a next record, or not? I mean, like: $result->hasNext()
Check the total number of returned rows using $mysqli->num_rows, then compare it to a counter in your loop that you increment with each loop iteration.
$row_cnt = $result->num_rows;
$loop_ct = 0;
while($row = $result->fetch_assoc()) {
if(++$loop_ct < $row_cnt) {
//do something
}
}
I prefer working efficiently and don't write extra code if it isn't needed. The following will work just fine:
$cnt = $result->num_rows;
while($row = $result->fetch_assoc()){
//....
$cnt--;
if($cnt == x){ //Where x is the number you want
//....
}
}
You're doing a while loop until you don't have any rows left, so the question is do you really need a test or do you just run the code you want at the end of your loop? If you need to test inside whether there will be a next row, you could do this:
$row = $result->fetch_assoc();
while (1) {
...
if (!$row = $result->fetch_assoc()) {
// No next row
break;
}
}
Which is pretty similar to what you're doing now.
Consider the code you posted
while ($row = $result->fetch_assoc()) {
//...
}
It is already doing that. check out the docs for mysqli_result::fetch_assoc, the while loop will break if $result->fetch_assoc() returns NULL. You don't need to manually check anything.
Either you can go with #McWayWeb or you can try this function mysqli_next_result().
Read it's manual here:- http://php.net/manual/en/mysqli.next-result.php
$_SESSION['lines'] is populated from a textbox that a user pastes into. Before I do anything with the data, I want to run it through a filter to see if any of the values they've input are NOT in the database.
foreach ($_SESSION['lines'] as $q) {
$multiSupplierQuery = "SELECT distinct supplier from allparts where quotePartNumber = '$q'";
$multiSupplierResult = mysqli_query($con, $multiSupplierQuery);
while ($row = mysqli_fetch_array($multiSupplierResult)) {
$multiSupplier = $row['supplier'];
}
if (!multiSupplier) {
unset($_SESSION['lines'[]);
}
}
The crux of this revolves around this statement:
if (!multiSupplier) {
unset($_SESSION['lines'[]);
}
What I'm trying to say is: each time we cycle through this, if multiSupplier doesn't exist, remove this particular element from the array.
my unset syntax is wrong though... how do I make it right?
You probably want to add a $ to your if statement. Change
if (!multiSupplier) {
to
if (!$multiSupplier) {
Also, to unset from the $_SESSION you need a key. Try changing
foreach ($_SESSION['lines'] as $q) {
to
foreach ($_SESSION['lines'] as $key=>$q) {
and then
unset($_SESSION['lines'][$key]);
It's not your unset usage, you just have an unnecessary opening square bracket.
unset($_SESSION['lines'[]);
should be
unset($_SESSION['lines']);
And you'll be good to go.
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=0;
while ($row=mysql_fetch_assoc()) {
if ($i==0) echo "First"
$i++;
}
Access directly to mysqli pointer? a php class like's Iterator?
Thanks.
I’d use this:
if ($row = mysql_fetch_assoc()) {
// process first item
while ($row = mysql_fetch_assoc()) {
// process following items
}
}
$first = true;
while ($row=mysql_fetch_assoc()) {
if ($first) echo "First"
$first = false;
}
If you're trying to use the first element for something special, then maybe something like:
$row=mysql_fetch_assoc();
//do stuff to first row
do {
//do stuff to all rows (including the first)
} while ($row=mysql_fetch_assoc());
Otherwise I have no idea what the question is and I'm not a PHP guy...
Do not have any method for know exactly position in all moment?
for example java iterator implements next or hasNext(), if !hasNext() the item is the last.
well, if i understand your question correctly, you want the first row and then iterate through the others:
$row = mysql_fetch_assoc(); // $row contains first row
while ($row = mysql_fetch_assoc()) { // loop through the rest of the rows
}