There is probably a very simple explanation for this, but I've had this code working for months, and now all of a sudden today it doesn't work.
I retrieve all the rows from a table. I have and object which is an entity model of the table I'm selecting from. As I read the rows from the associative result array, I'm storing each property using "$this->propertyName," and then I'm pushing each object to an array. Before I ended up with an array of objects, now I end up with an array of the same object repeated. Here's a code snippet:
$mdSelectALL_sql="SELECT * FROM member_data";
$mdSelectALL=mysql_query($mdSelectALL_sql,$mdConn);
if(!$mdSelectALL){
die('Error: ' . mysql_error());
}
else{
echo "RETURNING ALL MEMBER DATA RECORDS!!!<br>";
//store all records into array
while($row=mysql_fetch_array($mdSelectALL))
{
$this->mdId=$row['md_id'];
$this->mdFname=$row['md_fname'];
$this->mdLname=$row['md_lname'];
$this->mdEmail=$row['md_email'];
$this->mdTwitter=$row['md_twitter'];
$this->mdFacebook=$row['md_facebook'];
$this->mdMyspace=$row['md_myspace'];
$this->mdPhoneNumber=$row['md_phonenumber'];
$this->mdNotes=$row['md_notes'];
//store records in array
array_push($mdArray,$this);
}//end while
// print_r($mdArray); prints the array and each element is the last record encountered in the SQL retrieval
return $mdArray;
}//end else
My getters and setters look like this for each property:
function get_mdId(){
return $this->mdId;
}
function set_mdId($id){
$this->mdId=$id;
}
And suggestions or ideas?
-TU
Objects are passed around by reference. That means that when you change a value, that value will change everywhere that you have used that object.
As you are storing the same object every time - $this - you end up with an array of references to the same object.
To solve it, you can do:
$mdArray = array();
while($row=mysql_fetch_array($mdSelectALL))
{
$tmp_object = new MyObject; // fill in the name of your object...
$tmp_object->mdId=$row['md_id'];
...
array_push($mdArray, $tmp_object);
}
Related
I got this code from the internet. I don't know how the
$databases = current($res->toArray());
is working in the code. I am new in MongoDB and PHP. How is the current function able to retrieve all values? What exactly is executeCommand retrieving?
$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]);
$res = $mng->executeCommand("admin", $listdatabases);
$databases = current($res->toArray());
foreach ($databases->databases as $el) {
echo $el->name . "\n";
}
$res = $mng->executeCommand("admin", $listdatabases); executes the listDatabases command and assigns the result to $res. The result is a Cursor object, which has a toArray method.
The result of some $res->toArray() is, not surprisingly, an array. Its first element is an object that contains the list of databases.
Now, current is not a function specific to MongoDB. It's a standard PHP function that returns the current element of an array. Since the array was just created, the current element is the first element, the object that contains the list of databases.
So $databases = current($res->toArray()); gets you an object ($databases) that has a property databases which contains an array of database objects that you can iterate with foreach.
I know that the function fetchObject (http://www.php.net/manual/en/pdostatement.fetchobject.php) gives me the next row as an object of the specified class, but I want to get all the rows as an object of the specified class, does PDO has some function to this or I have to do it manually???
THanks!!
You are looking for PDOStatement::fetchAll:
PDOStatement::fetchAll — Returns an array containing all of the result set rows
Example usage:
$arr = $stmt->fetchAll(PDO::FETCH_CLASS, $class_name, $constructor_args);
If you do not need all of the objects in a single array, you will probably find iterating through all the rows to work just as well:
while ($obj = $stmt->fetchObject($class_name, $constructor_args)) {
// Process $obj
}
I've just started out learning PHP/JSON and I've kind of worked out how to output an array from an json file. My aim is to output all the album titles in <li>'s (in this case they are called collectionName in the json file). I think I maybe going about it the wrong way though.
$artistId = '644708';
$otherAlbumsURL = 'http://itunes.apple.com/lookup?id='. $artistId .'&entity=album';
$a = (array)json_decode(file_get_contents($otherAlbumsURL));
var_dump($a);
If you want an array, just use:
$a = json_decode(file_get_contents($otherAlbumsURL), true);
var_dump($a);
Setting the second parameter in json_decode to TRUE will give you an associative array instead of an object.
Judging from the response of the URL, you'll need to loop through the result like this in order to get any available collection names (the first array element doesn't contain a collection name because it is information about the artist. i.e. it isn't an album):
$artistInfo = $a['results'][0]; //Assign artist info to its own variable.
unset($a['results'][0]); //Delete artist info from the array.
//Loop through the results
foreach($a['results'] as $result){
//$result['collectionName'] has the collection name.
echo $result['collectionName'] . '<br>';
}
I'm attempting to use the VirusTotal API to return the virus scan for a certain file. I've been able to get my current PHP code to upload the file to VirusTotal as well as get the results in an array. My question is, how would I get the [detected] value from every virus scanner under the scans object? My PHP code is below as well as a link to the output of the array.
require_once('VirusTotalApiV2.php');
/* Initialize the VirusTotalApi class. */
$api = new VirusTotalAPIV2('');
if (!isset($_GET["hash"])) {
$result = $api->scanFile('file.exe');
$scanId = $api->getScanID($result);
$api->displayResult($result);
} else {
$report = $api->getFileReport($_GET["hash"]);
$api->displayResult($report);
print($api->getSubmissionDate($report) . '<br>');
print($api->getReportPermalink($report, TRUE) . '<br>');
}
http://joshua-ferrara.com/viruscan/VirusTotalApiV2Test.php?hash=46faf763525b75b408c927866923f4ac82a953d67efe80173848921609dc7a44
You would probably have to iterate each object under scans in a for loop and either store them in yet another array or echo them out of just want to print. For example
$detectedA = {nProtect, CAT-QuickHeal, McAfee...nth};
$datContainer = array();
for ($i = 0; i < $api.length ; i++){
//Either store in an array
$api->$scans->detectedA(i)-> detected = $datContainer(i);
//Or echo it all
echo $api->$scans->detectedA(i)->detected;
return true;
}
Granted that's probably not the way you access that object but the idea still applies.
This description of stdClass demonstrates how you can not only store arbitrary tuples of data in an object without defining a class, but also how you can cast an arbitrary object as an array - which would then let you iterate over the sub-objects in your case.
Or, if I've misunderstood your question and you're actually getting an array back from the VirusTotal API and not a stdClass instance, then all you need to do is loop.
Store the scans into an array (of scans), then just loop through the array as usual.
foreach($scans as $scan) echo $scan->detected;
Or, if I'm not quite understanding the question right, is detected an array (or an object)?
Edit because of your comments -
The object returned holds an object of objects, so you need to do some casting.
foreach((array)$scans as $scanObj) {
$scan=(array)$scanObj;
foreach($scan as $anti) {
print $anti->detected; } }
I have this object:
foreach(range(1,$oc->num_users) as $num) {
$user = 'user' . $num;
$$user = mysql_fetch_object(mysql_query("SELECT user".$num.", user".$num."_ready, FROM oc_db WHERE leader='".$_SESSION['username']."' "));
This gives objects named user1..X
later I have a simular function like this, where I use the $$user->$user that represent a username to connect to the db to get additional information.
$$user = mysql_fetch_object(mysql_query("SELECT x, y, z FROM user_db WHERE username='".$$user->$user."' "));
This also makes objects named user1..X, but instead of replacing the object created earlier I want to append this values to the object I created in the first function. $$user is the name of the objects. I would like to do something like $$user .= fetch_object in the last function, but off course it's not that simple.
In order to append one object to another you simply need to iterate through the first object and then assign each property you find to the second one:
$tmp = mysql_fetch_object(mysql_query("SELECT x, y, z FROM user_db WHERE username='".$$user->$user."' "));
foreach ($tmp as $key => $value) {
$$user->$key = $value;
}
As a couple of asides, if you are trying to access the user property of the object, then you should use $$user->user, as $$user->$user will be trying to access a numbered property (e.g. for object $user12, you're trying to access $user12->user12). I would also consider using an array, as fredley suggested (i.e. use $user[$num] instead of $user = 'user'.$num).
To approach your original question, instead of using the .= concatenation assignment operator, you could try adding a method to your user class, such as append, then using it to append the fetched object to your current object like $user->append( fetch_object(...));. In the append method, you can define your own rules for how a fetched object is added to your current user object.