I have a php comma seperated string
$string = (x,y,z)
I have a column in mysql that has items (y,z)
how do i compare the two and echo which items in $string are not in the column?
I think that should do the trick. Good Luck.
$myString="v1,v2,v3";
$stringA=explode(",",$myString);
$result=mysql_query("SELECT * FROM data");
while($row = mysql_fetch_array($result)){
$data=$row['dataColumn'];
if (!in_array($data,$stringA)) echo $data . "<br>";
}//end while
If you have data that needs to be exploded in the column we can go deeper.
$myString="v1,v2,v3";
$stringA=explode(",",$myString);
$result=mysql_query("SELECT * FROM data");
while($row = mysql_fetch_array($result)){
$data=$row['dataColumn'];
$da=explode(",",$data);
foreach($da as $value) if (!in_array($value,$stringA)) echo $data . "<br>";
}//end while
SELECT * FROM data. If the goal is to check the value of one column, it would be good to select only that column. It's also good to consider only fetching data for the rows that need to be tested instead of the whole table.I think you want to compute differente in two comma separated strings.
Just convert your strings in to array using explode and use array_diff
array_diff - Computes the difference of arrays
Example :
<?php
$array1=explode(",",$string);
$array2=explode(",",$yourstring_of_db_column);
$array1 = array("x", "y", "z");
$array2 = array( "y","z");
$result = array_diff($array1, $array2);
print_r($result);
?>
Be aware Values are compared using ===, so 1 and "1" are considered different.
the logic behind this is first explode the string with the explode(", ", $string) function.
So that it will become an array.
And on the other hand check the value with the function in_array(),
For example:
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
//output : 'ph' was found
you could solve this with one query, retrieving just the rows that do not match, eg.:
$string= "(str1, str2, str3)"; //formatted as the OP indicated
$input = explode(",",trim($string,"() "));
$filter = "(".$input[1].",".$input[2].")";
$sql = "select interestingColumn from greatTable where interestingColumn not like '".$filter."'";
$rez = mysql_query($sql);
while($row = mysql_fetch_array($rez)){
echo $row["interestingColumn"]."<br>\n";
}
this has the added benefit of retrieving fewer results from the database, which is desirable especially if you have a large dataset
edit : fixed a typo on the second line (thanks Michael)
$filter needs to be quoted and potentially escaped. You also have several syntax errors on the second line.