unserialize problem - php

I have another problem with my scripy now I have made it more advance, first off the count function doesnt work properly and it gives this error.
Warning: array_push() [function.array-push]: First argument should be an array in C:\wamp\www\social\add.php on line 42
Here is my script:
$query = mysql_query("SELECT friends FROM users WHERE id='$myid'");
$friends = mysql_fetch_array($query);
$friends2 = unserialize($friends['friends']);
if (count($friends2) == 0) {
//option 1
$friends2 = array($id);
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
}else{
//option 2
array_push($friends2, $id);
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");

It seems that $friends2 is not an array. Use the var_dump($friends2) function to see its value.

If you run this code right after having created the database but before putting any data in there, "unserialize($friends['friends']);" returns something other than an array. Probably an empty string. So in option 2, you may want to do something like this before array_push:
if (!is_array($friends2)) {
$friends2 = array();
}
This way, if the person has no friends by this point (sad.. but you'll fix it by pushing a new friend to them), an empty friends list gets initialized.
Plus, any time you see two identical lines of code in different parts of the "if" condition...
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
That's a signal that you should restructure your code so that you'd only have one copy of these lines.

This may not sound helpful, but your database design is quite stange.
Why is $friends2 not an array? Try to print_r () $friends after fetching an array to see if you actually get what you want from database in the first place.
Also, your count check is redundant. To add to an array, just go $friens2[] = $id; If $friends2 were empty, it will just make a new array of 1 element ($id), otherwise it will add it.

Your question contains the answer: unserialize($friends['friends']) seem to return non-array and count($friends2) is not zero - this can happen, for example, if number passed. Have you tried to examine the $friends['friends'] data? Simplest way would be to make additional check is_array($friends2)

Related

writing a second query based on results of the first - Not working

*MySQL will be upgraded later.
Preface: Authors can register in two languages and, for various additional reasons, that meant 2 databases. We realize that the setup appears odd in the use of multiple databases but it is more this abbreviated explanation that makes it seem so. So please ignore that oddity.
Situation:
My first query produces a recordset of authors who have cancelled their subscription. It finds them in the first database.
require_once('ConnString/FirstAuth.php');
mysql_select_db($xxxxx, $xxxxxx);
$query_Recordset1 = "SELECT auth_email FROM Authors WHERE Cancel = 'Cancel'";
$Recordset1 = mysql_query($query_Recordset1, $xxxxxx) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
In the second db where they are also listed, (table and column names are identical) I want to update them because they cancelled. To select their records for updating, I want to take the first recordset, put it into an array, swap out the connStrings, then search using that array.
These also work.
$results = array();
do {
results[] = $row_Recordset1;
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
print_r($results);
gives me an array. Array ( [0] => Array ( [auth_email] => renault#autxxx.com ) [1] => Array ( [auth_email] => rinaldi#autxxx.com ) [2] => Array ( [auth_email] => hemingway#autxxx.com )) ...so I know it is finding the first set of data.
Here's the problem: The query of the second database looks for the author by auth_email if it is 'IN' the $results array, but it is not finding the authors in the 2nd database as I expected. Please note the different connString
require_once('ConnString/SecondAuth.php');
mysql_select_db($xxxxx, $xxxxxx);
$query_Recordset2 = "SELECT auth_email FROM Authors WHERE auth_email IN('$results')";
$Recordset2 = mysql_query($query_Recordset2, $xxxxxx) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
The var_dump is 0 but I know that there are two records in there that should be found.
I've tried various combinations of IN like {$results}, but when I got to "'$results'", it was time to ask for help. I've checked all the available posts and none resolve my problem though I am now more familiar with the wild goose population.
I thought that since I swapped out the connection string, maybe $result was made null so I re-set it to the original connString and it still didn't find auth_email in $results in the same database where it certainly should have done.
Further, I've swapped out connStrings before with positive results, so... hmmm...
My goal, when working, is to echo the Recordset2 into a form with a do/while loop that will permit me to update their record in the 2nd db. Since the var_dump is 0, obviously this below isn't giving me a list of authors in the second table whose email addresses appear in the $results array, but I include it as example of what I want use to start the form in the page.
do {
$row_Recordset2['auth_email_addr '];
} while($row_Recordset2 = mysql_fetch_assoc($Recordset2));
As always, any pointer you can give are appreciated and correct answers are Accepted.
If you have a db user that has access to both databases and tables, just use a cross database query to do the update
UPDATE
mydb.Authors,
mydb2.Authors
SET
mydb.Authors.somefield = 'somevalue'
WHERE
mydb.Authors.auth_email = mydb2.Authors.auth_email AND
mydb2.Authors.Cancel= 'Cancel'
The IN clause excepts variables formated like this IN(var1,var2,var3)
You should use function to create a string, containing variables from this array.
//the simplest way to go
$string = '';
foreach($results as $r){
foreach($r as $r){
$string .= $r.",";
}
}
$string = substr($string,0,-1); //remove the ',' from the end of string
Its not tested, and obviously not the best way to go, but to show you the idea of your problem and how to handle it is this code quite relevant.
Now use $string instead of $results in query

table doesnt exist

I have created a query that loops through a group of table ID's to get a sum of their combined values. with error handling i get a "Table 'asterisk.custom_' doesn't exist" error and the query is killed obviously. but if i remove the error handling then i get an "mysql_fetch_array() expects parameter 1 to be resource" and the query completes as it should.
Thank in advance for your help.
include("currentday.php");
//---used for testing passing variables
//echo $customID[0];
//echo "<br>".$numrows;
$i = 0;
while($i<=$numrows)
{
mysql_select_db("asterisk") or die(mysql_error()); //This line determines the database to use
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
sum(vicidial_agent_log.pause_sec) as sumPause,
sum(custom_$customID[$i].d_amt) as sumDamnt,
sum(custom_$customID[$i].up_amt) as sumUpamnt,
sum(custom_$customID[$i].md_amt) as sumMdamnt,
sum(custom_$customID[$i].s_amount) as sumSamnt,
sum(vicidial_agent_log.dispo_sec)
FROM
vicidial_agent_log
INNER JOIN
vicidial_users
ON
(vicidial_agent_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$i]
ON
(vicidial_agent_log.lead_id = custom_$customID[$i].lead_id)
WHERE
vicidial_users.user = 'tcx'
GROUP BY
vicidial_users.full_name
ORDER BY
vicidial_agent_log.event_time DESC
";
$queryResult = mysql_query($query);// or die(mysql_error());
while ($rowResult = mysql_fetch_array($queryResult))
{
$pauseResult[] = $rowResult["sumPause"];
$sumdamntResult[] = $rowResult["sumDamnt"];
$sumupamntResult[] = $rowResult["sumUpamnt"];
$summdamntResult[] = $rowResult["sumMdamnt"];
$sumsamntResult[] = $rowResult["sumSamnt"];
}
//print_r($pauseResult);
//echo $pauseResult[0];
$i++;
}
Update:
The table exist in the database:
custom_2346579543413
custom_5466546513564
they are created by the dialer software and im calling them from another query that provides me the numeric part of the table name so this query loops through the values in customID array to make the query, Thanks again
Update:
Sammitch, thank you for the suggestion, however they did not work.
Solution:
Thanks Marc, you confirmed a suspicion i had in that it was looping correctly but for some reason it was looping more times that there we keys. so i echoed $i to confirm and in fact it was it was outputting 0,1,2,3 and since i know there is only 3 keys the last one didn't return anything and so error handling caught it and killed the entire loop and why it appeared correct when error handling was turned off. The solution was actually rather simple and it was in the while loop evaluation string i had used
while($i<=$numrows)
while($i<$numrows)//this worked, the equals part of that gave it an extra loop
and the query completes as it should.
No, it doesn't. "mysql_fetch_array() expects parameter 1 to be resource" means "the query failed, and you didn't bother to check before calling mysql_fetch_array()".
Your problem is that variable expansion inside of a string doesn't like array indexes. You need to change:
"sum(custom_$customID[$i].d_amt) as sumDamnt,"
To:
"sum(custom_{$customID[$i]}.d_amt) as sumDamnt,"
Or:
"sum(custom_" . $customID[$i] . ".d_amt) as sumDamnt,"
For it to work properly.

Array not containing values when using "in_array" (php) w/ mysql_query

I continue to struggle with array! This is probably easy to answer.
I'm retrieving a data set from MYSQL w/ PHP. I get an array that has the 1st row (ala the mysql_fetch_array). Typically I would just loop through this and get each value, but in this case I'm already in the middle of a loop and I need to find out if a particular value exists in the full data set (which will be more than 1 row).
I figured I could just loop through and put all the values into an array with something like:
$query = "SELECT MapId FROM Map Where GameId = $gl_game_id";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
$map_set = array();
while($row = mysql_fetch_assoc($result_set)) {
$map_set[] = $row;
}
When I print_r this, I do in fact get the full data set (e.g. all rows of MapId from table Map).
So now, when I go to look in there and see if a value (that is coming out of this other loop) exists, it won't find it.
So my code looks like:
if (in_array($i, $map_set)) {
echo "yes, it's there baby!";
}
But it doesn't work. I tried hard coding the array, and that does in fact work. So there is simply something wrong with the way I'm constructing my array that this function doesn't like it.
if (in_array($i, array(40,12,53,65))) {
echo "yes, it's there baby!";
}
arrrg... I do hate being a noobie at this.
Function mysql_fetch_assoc returned array.
If you make print_r($map_set) then you will see that is 2-dimension array. Sure in_array not worked.
Just replace $map_set[] = $row; by $map_set[] = $row["MapId"]; and then try again.

php count returning 1 not 0 from mysql_query when empty

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

Is this a PHP or MySQL bug?

$allUsersResult = mysql_query("SELECT * FROM users");
// the purpose of this line was to grab the first row for use
// separately in a different area than the while loop
$user = mysql_fetch_assoc($allUsersResult);
while($users = mysql_fetch_assoc($allUsersResult)){
// the first row is not available here
}
So is this a bug or is it my fault for doing it wrong?
PS: this is only for example. I'm not using both $user and the while loop right next to each other like this, they are used in different places in the script.
You need to drop
$allUsers = mysql_fetch_assoc($allUsersResult);
It's taking your first result row.
Answer to new question: No. It is not a design flaw in PHP. It's a flaw in your program design. You need to rethink what you are doing.
Why do you need the first value separated out? Are you relying on it to be a specific row from your table all of the time? If you alter your table schema it's very possible that the results will be returned to you using some other sorted order.
Perhaps if you tell us what you are trying to do we can give you some design suggestions.
It is your fault. By calling $allUsers = mysql_fetch_assoc($allUsersResult); first, you already fetch the first row from the result set. So just remove that line, and it should work as expected.
edit: Per request in comment.
$user = mysql_fetch_assoc($allUsersResult);
if ( $user ) // check if we actually have a result
{
// do something special with first $user
do
{
// do the general stuff with user
}
while( $user = mysql_fetch_assoc($allUsersResult) );
}
Which is considered as bad code by some IDEs (two statements in one row). Better:
$allUsersResult = mysql_query("SELECT * FROM users");
$user = mysql_fetch_assoc($allUsersResult);
while($user){
// do stuff
doStuff($user)
// at last: get next result
$user = mysql_fetch_assoc($allUsersResult)
}
When you use mysql_fetch_assoc(), you are basically retrieving the row and then advancing the internal result pointer +1.
To better explain, here is your code:
$allUsersResult = mysql_query("SELECT * FROM users");
//Result is into $allUsersResult... Pointer at 0
$user = mysql_fetch_assoc($allUsersResult);
// $user now holds first row (0), advancing pointer to 1
// Here, it will fetch second row as pointer is at 1...
while($users = mysql_fetch_assoc($allUsersResult)){
// the first row is not available here
}
If you want to fetch the first row again, you do not need to run the query again, simply reset the pointer back to 0 once you have read the first row...
$allUsersResult = mysql_query("SELECT * FROM users");
//Result is into $allUsersResult... Pointer at 0
$user = mysql_fetch_assoc($allUsersResult);
// $user now holds first row (0), advancing pointer to 1
// Resetting pointer to 0
mysql_data_seek($allUsersResult, 0);
// Here, it will fetch all rows starting with the first one
while($users = mysql_fetch_assoc($allUsersResult)){
// And the first row IS available
}
PHP Documentation: mysql_data_seek()
I'll go ahead and answer my own question on this one:
$allUsersResult = mysql_query("SELECT * FROM users");
// transfer all rows to your own array immediately
while($user = mysql_fetch_assoc($allUsersResult)){
$allUsers[] = $user;
}
// use first row however you like anywhere in your code
$firstRow = $allUsers[0];
// use all rows however you like anywhere in your code
foreach($allUsers as $user){
// do whatever with each row ($user). Hey look they're all here! :)
}

Categories