php MySQL fetch printing double? - php

When I make a sql query and echo it out it repeats the first row twice
$sql = 'SELECT one,two,three FROM justAnExampleForSO where one = one';
$info = mysql_query(sql);
if(mysql_num_rows($info )>0){
while ($row = mysql_fetch_array($info )) {
foreach($row as $key => $var)
{
if($key == 'one')
echo $var.",";
else if($key == 'two')
echo $var.",";
else if($key == 'three')
echo $var.";";
}
}
}
so for example say I am attempting to get cols one, two, three
When the output is echoed it would echo
one, one, two,three;
I am not sure if this is a duplicate of this question or not because I couldn't full understand his problem. Fetch array function doubling values in each position of array?

Because mysql_fetch_array returns both numerically indexed values and string indexes, and due to the fun of type casting rules "one" equals 0. Use === instead of == to prevent that, or use mysql_fetch_assoc to forgo the numerical indexes you're not using anyway.
You should also be doing it much more simply than a foreach..if..else:
echo $row['one'], ', ', $row['two'], ', ', $row['three'], ';';

Related

Retrieving values crossing arrays gives unlogic result

In Drupal context, while printing checked exposed filters in a somehow standard code snippet, I can't print more than one value, and I can't find the missing logic of my foreach loop :
<?php
foreach ($exposed_filters as $filter => $value) {
if ($filter == 'foo') {
$field = field_info_field('field_foo');
$allowed_values = list_allowed_values($field);
//returns an array with 14 string values & numeric keys
//e.g array(0=>'bla', 1=>'bar', 2=>'xx', 3=>'yy')
$h = explode(',', $value);//returns checked ids of foo filter e.g array(0 => 2, 1=>3)
$exp_heb = '';
foreach ($h as $k=>$v) {
$exp_heb .= $allowed_values[$v] . ', ';
}
$exp_heb = substr($exp_heb, 0, -2);
print $exp_heb;
}
}
?>
Should return : xx, yy but I get xx,,
I checked step by step printing out my arrays, values... everything's looks fine but result is wrong. Do I need a rest ???
This is dpm($allowed_values) output
May be this line cuts your output?
$exp_heb = substr($exp_heb, 0, -2);
I got it working. I have to get the integer value of my variable, before passing it as a key :
foreach ($h as $k=>$v) {
$exp_heb .= $allowed_values[intval($v)] . ', ';
}
For a reason I would be glad to be taught, even if it's always an id, and prints out a number, first time it's passed as integer, but then not.

PHP - Search array for string

I have a page with a form where I post all my checkboxes into one array in my database.
The values in my database looks like this: "0,12,0,15,58,0,16".
Now I'm listing these numbers and everything works fine, but I don't want the zero values to be listed on my page, how am I able to search through the array and NOT list the zero values ?
I'm exploding the array and using a for each loop to display the values at the moment.
The proper thing to do is to insert a WHERE statement into your database query:
SELECT * FROM table WHERE value != 0
However, if you are limited to PHP just use the below code :)
foreach($values AS $key => $value) {
//Skip the value if it is 0
if($value == 0) {
continue;
}
//do something with the other values
}
In order to clean an array of elements, you can use the array_filter method.
In order to clean up of zeros, you should do the following:
function is_non_zero($value)
{
return $value != 0;
}
$filtered_data = array_filter($data, 'is_non_zero');
This way if you need to iterate multiple times the array, the zeros will already be deleted from them.
you can use array_filter for this. You can also specify a callback function in this function if you want to remove items on custom criteria.
Maybe try:
$out = array_filter(explode(',', $string), function ($v) { return ($v != 0); });
There are a LOT of ways to do this, as is obvious from the answers above.
While this is not the best method, the logic of this might be easier for phpnewbies to understand than some of the above methods. This method could also be used if you need to keep your original values for use in a later process.
$nums = '0,12,0,15,58,0,16';
$list = explode(',',$nums);
$newList = array();
foreach ($list as $key => $value) {
//
// if value does not equal zero
//
if ( $value != '0' ) {
//
// add to newList array
//
$newList[] = $value;
}
}
echo '<pre>';
print_r( $newList );
echo '</pre>';
However, my vote for the best answer goes to #Lumbendil above.
$String = '0,12,0,15,58,0,16';
$String = str_replace('0', '',$String); // Remove 0 values
$Array = explode(',', $String);
foreach ($Array AS $Values) {
echo $Values."<br>";
}
Explained:
You have your checkbox, lets say the values have been converted into a string. using str_replace we have removed all 0 values from your string. We have then created an array by using explode, and using the foreach loop. We are echoing out all the values of th array minux the 0 values.
Oneliner:
$string = '0,12,0,15,58,0,16';
echo preg_replace(array('/^0,|,0,|,0$/', '/^,|,$/'), array(',', ''), $string); // output 12,15,58,16

PHP find equal variables

Is there a way to easily check if the values of multiple variables are equal? For example, in the code below I have 10 values, and it's cumbersome to use the equal sign to check if they're all equal.
<?
foreach($this->layout as $l):
$long1=$l['long1_campaignid'];
$long2=$l['long2_campaignid'];
$long3=$l['long3_campaignid'];
$long4=$l['long4_campaignid'];
$long5=$l['long5_campaignid'];
$long6=$l['long6_campaignid'];
$long7=$l['long7_campaignid'];
$long8=$l['long8_campaignid'];
$long9=$l['long9_campaignid'];
$long10=$l['long10_campaignid'];
endforeach;
?>
for example
if $long1=3,$long2=7,$long3=3,$long4=7,$long5=3 etc,
i need to retrieve $long1=$long3=$long5 and $long2=$long4
I think this is what you're looking for:
<?
foreach($this->layout as $l):
$m = array_unique($l);
if (count($m) === 1) {
echo 'All of the values are the same<br>';
}
endforeach;
?>
I assuming that you are looking to see if all of the values in the array are the same. So to do this I call array_unique() to remove duplicates from the array. If all of the values of the array are the same this will leave us with an array of one element. So I check for this and if it is true then all of the values are the same.
The example showed at the question is about "grouping" not directly about "find equal variables".
I think this simple "grouping without change the order" algorithm is the answer... Other algorithms using sort() are also easy to implement with PHP.
<?
foreach($this->layout as $l) {
$m = array();
foreach($1 as $k=>$v) // keys 'longX' and values
if (array_key_exists($v,$m)) $m[$v][] = $k;
else $m[$v] = array($k);
foreach ($m as $val=>$keys)
if (count($keys)>1) echo "<br/> have SAME values: ".join(',',$keys)
}
?>
About "find equal variables"
Another (simple) code, see Example #2 at PHP man of array_unique.
<?
$m = array_unique($this->layout);
$n = count($m);
if ($n == 1)
echo 'All of the values are the exactly the same';
elseif ($n>0)
echo 'Different values';
else
echo 'No values';
?>
The "equal criteria" perhaps need some filtering at strings, to normalize spaces, lower/upper cases, etc. Only the use of this "flexible equal" justify a loop. Example:
<?
$m = array();
foreach($this->layout as $l)
$m[trim(strtolower($1))]=1;
$n = count(array_keys($m));
if ($n == 1)
echo 'All of the values are the exactly the same';
elseif ($n>0)
echo 'Different values';
else
echo 'No values';
?>
If #John Conde's answer is not what you are looking for and you want to check for one or more of the same values in the collection, you could sort the array and then loop through it, keeping the last value and comparing it to the current value.

How to handle my data?

Edit: The aim of my method is to delete a value from a string in a database.
I cant seem to find the answer for this one anywhere. Can you concatenate inside a str_replace like this:
str_replace($pid . ",","",$boom);
$pid is a page id, eg 40
$boom is an exploded array
If i have a string: 40,56,12 i want to make it 56,12 however without the concatenator in it will produce:
,56,12
When I have the concat in the str_replace it doesnt do a thing. Is this possible?
Answering your question: yes you can. That code works as you would expect it to.
But this approach is wrong. It will not work for $pid = 12; (last element, without trailing coma) and will incorrectly replace 40, in $boom = '140,20,12';
You should keep it in array, search for unwanted value, if found unset it from the array and then implode with coma.
$boom = array_filter($boom);
$key = array_search($pid, $boom);
if($key !== false){
unset($boom[$key]);
}
$boom = implode(',',$boom);
[+] Your code does not work because $boom is an array, and str_replace operates on string.
As $boom is an array, you don't need to use array on your case.
Change this
$boom = explode(",",$ticket_array);
$boom = str_replace($pid . ",","",$boom);
$together = implode(",",$boom);
to
$together = str_replace($pid . ",","",$ticket_array);
Update: If you want still want to use array
$boom = explode(",",$ticket_array);
unset($boom[array_search($pid, $boom)]);
$together = implode(",",$boom);
After you have edited it becomes clear that you want to remove the value of $pid from the array $boom which contains one number as a value. You can use array_search to find if it is in at if in with which key. You can then unset the element from $boom:
$pid = '40';
$boom = explode(',', '40,56,12');
$r = array_search($pid, $boom, FALSE);
if ($r !== FALSE) {
unset($boom[$r]);
}
Old question:
Can you concatenate inside a str_replace like this: ... ?
Yes you can, see the example:
$pid = '40';
$boom = array('40,56,12');
print_r(str_replace($pid . ",", "", $boom));
Result:
Array
(
[0] => 56,12
)
Which is pretty much like you did so you might be looking for the problem at the wrong place. You can use any string expression for the parameter.
It might be easier for you if you're unsure to create a variable first:
$pid = '40';
$boom = array('40,56,12');
$search = sprintf("%d,", $pid);
print_r(str_replace($search, "", $boom));
You should store your "ticket array" in a separate table.
And use regular SQL queries (UPDATE, DELETE) to manipulate it.
A relational word in the name of your database is for the reason. And you are abusing this smart software with such a barbaric approach.
You could use str_split, it converts a string to an array, then with a foreach loop echo all the values except the first one.
$numbers_string="40,56,12";
$numbers_array = str_split($numbers_string);
//then, when you have the array of numbers, you could echo every number except the first separating them with a comma
foreach ($numbers_array as $key => $value) {
if ($key > 0) {
echo $value . ", ";
}
}
If you want is to skip a value not by it's position in the array, but for it's value then you could do this instead:
$unwanted_value="40";
foreach ($numbers_array as $key => $value) {
if ($value != $unwanted_value) {
echo $value . ", ";
}
else {
unset($numbers_array[$key]);
$numbers_array = array_values($numbers_array);
var_dump($numbers_array);
}
}

PHP display problem?

For some reason when an array has for example, four values it will display all four values four times I just want the values to be displayed one time.
How can I fix this problem? Note the first echo works perfectly.
Here is the code.
if (count($array) == 1){
echo $array[$x] . " one value has been entered";
} else {
echo implode(", ", $array) ." you entered more then one value;
}
Because $x obviously isn't the index of the first element of the array. Use the correct index. Or if you don't know what it is, just use reset():
if (count($array) == 1) {
echo reset($array) . ' one value has been entered';
} else {
echo implode(', ', $array) . ' you entered more than one value';
}
It might be helpful to dump the array to see what it actually contains:
print_r($array);
$x is not set in your code or just meaningless. If you have just one array item you can print it with the simple echo $array[0];

Categories