I was hoping someone could show how to properly append an array created with an sql query with data from a second query.
I have an array I created from a mysql resource which is correct.
while($row = mysql_fetch_array($result)){
$first_pass[] = $row;
}
But before I finish with the $first_pass array I want to do a second query, so inside the while loop before the $first_pass array I added;
$p = $row['productid'];
$gle = mysql_query("SELECT value FROM `extra_field_values` WHERE productid = $p' AND fieldid ='11' ");
$goog = mysql_fetch_row($gle);
$row['google_cat'] = $goog[0];
my question is, no matter how I add this query to the existing array, when I dump it, it does not look like just another index added to the array. I have tried the mysql_fetch_row with my own created index and I have tried using mysql_fetch_array but then it shows as another array in the array.
I think it will function fine the way it is but it does not look proper.
This is what the dump looks like:
array0
=>array
0 => string '3614' (length=4)
'variantid' => string '3614' (length=4)
1 => string '1406' (length=4)
'productid' => string '1406' (length=4)
2 => string '180-GL-QT-CAY-M' (length=15)
'productcode' => string '180-GL-QT-CAY-M' (length=15)
google_cat => 'Clothing> Gloves'
where google_cat looks nothing like the rest of the array. So any input is appreciated.
Thanks
The difference is, your initial $row is populated using mysql_fetch_array() which defaults to using the MYSQL_BOTH fetch method.
This creates an array using both numeric indices and column name keys.
When you append your 'google_cat' key, you're only creating an associative index.
Unless you're actually going to use the numeric indices, I'd recommend sticking to mysql_fetch_assoc() instead of mysql_fetch_array()
Actually, what I really recommend is ditching the mysql extension all together and moving to PDO.
I think you have an error in your MySQL syntax. Try:
$gle = mysql_query("SELECT value FROM `extra_field_values` WHERE productid = '". $p ."' AND fieldid = '11';");
You could also try replacing $row['google_cat'] = $goog[0]; with:
$row['google_cat'] = $goog[0][0];
...So it gives you the interior array of the first array in the multidimensional row return array. (Array array arraaayyyyyy...)
First use the same method to get your arrays from mysql (either mysql_fetch_array or mysql_fetch_row) not both.
then you can use
array_merge($row, $goog);
to concatenate the arrays together. beware the warning that if two elements have the same associative key the last one in the list will be the value of that key.
http://php.net/array_merge
Error in your syntax man!
$gle = mysql_query("SELECT value FROM `extra_field_values` WHERE productid = $p' AND fieldid ='11' ");
Is missing an apostrophe...
Should be:
$gle = mysql_query("SELECT value FROM `extra_field_values` WHERE productid = '$p' AND fieldid ='11' ");
Related
I am trying to select a certain numerical value that is separated by comma. The values are from a mysql db. I try to use explode the column but am not sure how to catch a certain value.
Any help would be appreciated.
Code
$query = mysql_query("SELECT id_array FROM values WHERE id='$id'");
while($result = mysql_fetch_assoc($query))
{
$get_id = $result['id_array'];
}
$exact = explode(",",$get_id);
Assuming you're storing a comma-separated list of values in column id_array, i.e.
12,17,44,13
After you've exploded the result you've got an array of the form
$exact is an array:
(
[0] => '12'
[1] => '17'
[2] => '44'
[3] => '13'
)
Now you want to know if 17 is an element of this array. Right? You can do it with in_array()
$check = in_array(17, $exact); // true, if found as in my example.
// Please note, that it's important not to search in strict mode.
// Test with 100, not in list
$check = in_array(100, $exact) // returns false
Maybe I misunderstood completely your problem. In this case please state with example data what your problem really is. What you've tried and where you got stuck.
PS: I wouldn't recommend storing comma separated lists in MySQL and it would be a great idea to drop the use of the mysql_* functions because they're deprecated. Use mysqli or PDO instead.
In the project that I am creating, I have a mysql column that is an array of different pieces of data from the database. These pieces of data have info that I want to display. In order to separate these items in the array I used,
$get_query = mysql_query('Select array FROM data');
while($dataRow = mysql_fetch_assoc($getfrnd_query)) {
$array = $dataRow['array'];
if($array != "") {
$data_from_array_column = explode("," $array);
$getdata = mysql_query("SELECT * FROM info WHERE item = $data_from_array_column");
//Then I used a mysql_fetch_assoc to get data based on the item.
}
}
When I run this code, I get an error "Array to string conversion on the line with $getdata".
Is there any way to get this to work?
Thank you.
The problem is that explode returns an array containing the strings in between the character(s) you used as a delimiter (, in your case), not a string.
PHP is getting mad because it doesn't know how to convert your array to a string automatically. So, you will need to convert it yourself. The options are:
You want to select the row where item is equal to the nth element in the array, $data_from_array_column. If this is the case, you need to insert the following line of code after your explode:
$data_from_array_column = $data_from_array_column[0];
If you want to select where it matches any of the elements in the $data_from_array_column array, it will get more complicated. You would need to add this line after the explode:
$data_from_array_column = implode("' OR item='",$data_from_array_column);
and change your query on the next line to:
$getdata = mysql_query("SELECT * FROM info WHERE item='$data_from_array_column'");
This will create a MySQL query that looks some thing like this:
SELECT * FROM info WHERE item='foo' OR item='bar' OR item='bla'
While working with PHP ,handling connection's with Database (MySQL)
$result = mysql_query('select * from products');
$row = mysql_fetch_array($result);
And yesterday founded out that array $row had Duplicate data within.
First you have Data's selected from database arranged in Indexes like : $row[0] = ID; than you also could find $row['ID'] = ID.
So is this only a feature of the Framework ,which copies data Virtually or are these Data's stored twice in array .
To get only one value set, you need to pass a second parameter to mysql_fetch_array.
either "MYSQL_ASSOC" to get an associative array, or "MYSQL_NUM" to get a normal array.
Example:
$row = mysql_fetch_array($result, 'MYSQL_ASSOC')
This will return:
$row['id']
Documentation
Straight from the manual:
mysql_fetch_array — Fetch a result row as an associative array, a
numeric array, or both
The prototype of the function says that
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
meaning that it returns both arrays by default - that is - duplicating the info
mysql_fetch_array fetches a result row as an associative array, a numeric array, or both. Please see: mysql_fetch_array.
Each row in $result has an index, a name and a value. You can look up a row's value by either index or name.
See the documentation for mysql_fetch_array()
Default setting is to fetch an array with both numeric and associative array. See PHP manual to change that.
How can I add a value into an array in a database row, and then later on, when I want to get values of the array, simply display each different array value on a new line?
Also, how do arrays work in mysql and how to get the value of it?
Filed testField has serialized data.
$arrayData = array('one','two','three');
$serializedData = serialize($arrayData);
Mysql insertion:
insert INTO table ('testField') Values ($serializedData);
To get data:
select testField from table where id=1
You are getting here some string value. Then you should unserialize this string to get array:
$arrayData = unserialize($selectResultValue);
Look here for more details about serialize function:
http://php.net/manual/en/function.unserialize.php
MySQL does not have a native array data type. So, your first step is to figure out how you will store the elements of the array in a MySQL table.
Will you store each array element in its own database row?
elem val
1 value1
2 value2
...
n valuen
Or will you store the arraw as a series of concatenated values in a single row, something like this?
values
value1,value2,value3,...,valuen
In the first case, you can update a single array element easily:
UPDATE array SET val=newValue
WHERE elem=updatedElement
In the second case, you'll have to read the values column, break it out (deserialize it) into an array, change the element or elements you want to change, then gather it up (serialize it) back into a values column, and update your mySQL table. #Anthony pointed this out.
You need to answer the question about how you're storing the array before you can start to figure out how you will update it.
save array
$foo = array(1,2,3);
mysql_query(sprintf("INSERT INTO some_table ('foo') VALUES ('%s')", serialize($foo));
foo will appear as a string 1,2,3 in the database now
fetch array
$result = mysql_query("SELECT id, foo FROM some_table")
$item = mysql_fetch_object($result);
$foo = $item->foo;
$foo = unserialize($foo);
add data to array
$foo[] = 4;
$foo = array_uniq($foo); // you might want to ensure only unique values
mysql_query(sprintf("UPDATE some_table SET foo='%s' WHERE id=%d", serialize($foo), $item->id);
foo will appear as a string 1,2,3,4 in the database now
I am trying to get a count and I am getting 1 instead of 0 from it. I have looked thoroughly though the web and this site. I have even been trying to figure it out on my own for a long time. I keep coming empty handed here.
So Basically what I am trying to do is make a like system for my users. I can get everything to work correctly the count works except for one thing. When they have liked it it returns 1 not 0 which it should be.
Here is my code for the count. I am not posting all the coding for security reasons and it really doesn't need to since its about the counting part not the rest.
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$like1 = $row['like_array'];
$like3 = explode(",", $like1);
$likeCount = count($like3);
}
So here is the code that determines the number. Any ideas what is wrong with this? Why its returning 1 not 0 when the item is empty?
// you do escape your id right??? (sql injection prevention)
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$likeCount = 0;
$like1 = trim($row['like_array']);
if ($like1) {
$like3 = explode(",", $like1); // exploding emtpy string would result in array('')
$likeCount = count($like3);
}
}
Calling explode on an empty string gives an array containing the empty string. This is one element, not zero.
I would suggest that you change your database design if possible so that you don't store the values separated by commas. Use a separate table instead.
If you can't change the database design you can handle the empty string separately.
count() returns the number of indexes in an array or something in an object (PHP: count - Manual).
if a string var is used rather than an array or object it returns 1. it has to get a null value in order to return 0.
you can give it a go by trying:
print count("");
and
print count(null);
You'll have better luck if you use explode() to break the sql output into an array and then run a check with an if statement. Something like the following:
$like3 = explode(',',$like1);
if (count($like1)=1 && $like1[0] == '')
// etc ..
I hope this helps