remove element from array based on sql query - 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.

Related

while loop is not working upon selecting multiple colums from a table

i have a table with 5 columns like TABLE(a,b,c,d,e).
now i want to select all the columns from TABLE.but the script is not workling once the while loop starts.
my php code is:
include_once $_SERVER['DOCUMENT_ROOT'].'/include/db.inc.php' ;
$sql="select * from TABLE";
$result = mysqli_query($link,$sql );
if (!$result)
{
include_once "wall.html.php";
echo'<tr><td align="center"> OOOOPPPPPSSS!!!SORRY,UNABLE TO DISPLAY LATEST 25 TOPICS</td></tr>';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$as[]=$row['a'];
$bs[]=$row['b'];
$cs[]=$row['c'];
$ds[]=$row['d'];
$es[]=$row['e'];
}
foreach($as as $x)
{
$name=$x;
}....................and so on
i have checked and debuged in many ways.what i noticed the script is not executing after while loop.
you forgot to write $ before variables:
$as[]=$row['a'];
^------------
bs[]=$row['b'];
cs[]=$row['c'];
ds[]=$row['d'];
es[]=$row['e'];
What about using array_push()? Also, use print_r() for $as[] and all the arrays you got and paste the output here so we get a clearer idea of what the issue exactly is.
Try this and tell what print_r() function is printing so that we can identify the problem.
while ($row = mysqli_fetch_array($result))
{
$as[]=$row['a'];
$bs[]=$row['b'];
$cs[]=$row['c'];
$ds[]=$row['d'];
$es[]=$row['e'];
}
print_r($as);
foreach($as as $x)
{
$name=$x;
}
First remove the brackets from $as[], the result of $row['a'] will not be an array.
And that's the reason the foreach is not working, you're not getting an array back.
If the resulting $as is empty, but there is something in your database, make sure the rownames are valid.
Use $row[0] instead of $row['A'].
Debug your code using print_r($row) to the see the contents of the results.

check duplicated data from selected data

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'];
}
}

PDO - Foreach with Array Respect

using PDO, I receive 1+ rows and turn them into an array like this:
while($row = $car_sales->fetch(PDO::FETCH_ASSOC)){
$car_id_array[] = $row["car_id"];
$car_type_array[] = $row["car_type"];
$dealer_id_array[] = $row["dealer_id"];
$buyer_id_array[] = $row["seller_id"];
}
I'm trying to simply "mix" each level of the array to act as a unit and go down the foreach loop together, submitting the $q query in order. In other words, something like this:
foreach($dealer_id_array as $dealer_id) {
if ($car_type=='new') {
if ($dealer_id==$buyer_id){
$q = 'UPDATE car_sales SET new_cars=new_cars+1 WHERE dealer_id=:dealer_id';
} else if ($dealer_id!=$buyer_id){
$q = 'UPDATE car_sales SET new_cars=new_cars-1 WHERE dealer_id=:dealer_id';
} else if ($car_type=='old') {
if ($dealer_id==$buyer_id){
$q = 'UPDATE car_sales SET old_cars=old_cars+1 WHERE dealer_id=:dealer_id';
} else if ($dealer_id!=$buyer_id){
$q = 'UPDATE car_sales SET old_cars=old_cars-1 WHERE dealer_id=:dealer_id';
}
$car_update = $dbhandle->prepare($q);
$car_update->execute(array(':dealer_id' => $dealer_id));
}
The loop should run with the first array values if there is only one value retrieved from the while loop. If there are more, the foreach should run as many times as there are dealer_ids from the while loop, while respecting the order. This example won't work, but I'm looking for possible solutions to solve this issue correctly. What do you think would be the most efficient way to do this?
I might be misunderstanding you, but I believe if you just replaced your foreach loop with a for loop, and counted one of the arrays you would solve your issue:
for($i = 0; $i < count($dealer_id_array); $i++) {
and then simply using $i to access the correct item in your arrays:
$car_type_array[$i];
But having said that, I don't really see the point of the initial four arrays in the first place. Could you not just directly execute the code inside the foreach loop straight inside the while loop in the first place?
EDITED: to fix code example

Saving 2 variable's values for later use

I tried to make the title of this most the most descriptive as possible, as I don't know how to do this... I know the best way will be value storage in some form of array.
My question is this, I have this query where I need to pic the tag name and the correspondent id for a later comparison and use ($tag_nome is collected by $_GET):
$resultado2 = mysql_query("SELECT tag.tag_nome, rel_frasetag.id_tag
FROM tag, rel_frasetag
WHERE rel_frasetag.id_tag = tag.id_tag AND
rel_frasetag.id_frase='$id_frase'") or die(mysql_error());
while($res2 = mysql_fetch_array($resultado2))
{
$tag_nome2 = utf8_encode($res2['tag_nome']);
$id_tag = $res2['id_tag'];
}
I already tried some things like array_push() but couldn't get it to work.
At the end of this snippet I'm comparing $tag_nome2 against $tag_nome to see if they match. If so, it will echo one link with the corresponding $tag_nome2 and $id_tag, and if not will echo pretty much the same thing, with a different class on the link.
My best guess as far as what you want to do is the following:
if( $tag_nome2 == $id_tag )
{
// do something
}
else
{
// no match
}
Perhaps though, you're saying your variable names are being overwritten? You're inside of a while loop, so the values they'll ultimately receive will be that of $res2[] at the end of the last iteration of your loop.
And if you're saying you want to save your rows for later, you can do:
$holder = array();
$res = mysql_query("");
while( $row = mysql_fetch_assoc($res) )
{
$holder[] = $row;
}
print_r($holder);

PHP: Unexpected behavior: foreach... {$array['country'][] = $value['country']}

Why does the operator
$array['country'][] return what logically would be $array[]['country']?
What I am saying is this. If you want to extract from a MySQL array, the value of ['country'] for every row, [1],[2]...[n], you have to use
$array['country'][]
despite fact that they are ordered as
$array['row#']['country']
Is this because PHP is reading something backwards, or because I am just lacking some fundamental array information?
FULL-ish code here
$result = array();
foreach($data as $value){
$array['country'][] = $value['country'];
$array['report'][] = $value['report'];
}
$data = $array;
Let me know if I am just dumb... I can't really grasp why this is working this way.
get an id from the db
SELECT id,country,report from yourdb
while ($row = mysql_fetch_array($result)) {
$array['country'][$row['id']] = $row['country'];
$array['report'][$row['id']] = $row['report'];
}
create an id
SELECT country,report from yourdb
$i=0
while ($row = mysql_fetch_array($result)) {
$array['country'][$i] = $row['country'];
$array['report'][$i] = $row['report'];
$i++
}
Why does the operator
$array['country'][]
return what
logically would be
$array[]['country']?
It is because you are constructing the array in that way:
If you use $array['country'][] = $value['country'];, you are adding a new value to the sub-array which is part of the containing array under the country key. So it will be mapped to $array['country'][], you cannot expect otherwise.
If you want it to map to array[]['country'], then (using part of code from
#Lawrence's answer), you'd have to add the new values using explicit numerical indexes as the key:
SELECT country,report from yourdb
$i=0;
while ($row = mysql_fetch_array($result)) {
$array[$i]['country'][] = $row['country'];
$array[$i]['report'][] = $row['report'];
$i++;
}
Assuming that $data has been built by you using a loop like what you pasted in the comments (while($row=mysql_fetch_assoc($result)){$data[]=$row;}) then my answer would be because that's exactly what you asked PHP to do.
The notion $data[] = some-value-here means take that value and add it with to the end of $data array with an auto-generated key I just don't care. That is, PHP will basically see what the last item's key is, add 1 and use that as the key for the item you are adding to the array.
So what you are doing with that loop is building an array whose keys are numbers starting from 0 and incrementing (+1 each cycle, this is the [] effect) and using these keys for the rows you are getting off the database result set.
If you want to access $data in the way you described, then you have to change the way you are building it. See Lawrence Cherone's answer for that.

Categories