So currently I am having some issues with trying to access an element in this multidimensional array. So what I am trying to do is to create 3 different arrays of different classes, and then return them in array at the end.
The problem comes when I am trying to accsess one of the array's in the $result array. I have checked and there are elements in the array's but I am unable to access them.
public function search($searchString) : array
{
$bloggArr[] = array();
$bloggerArr[] = array();
$innleggArr[] = array();
$stmt = $this->db->prepare("SELECT * FROM blogg WHERE
bnavn=:bnavn");
$stmt->bindParam('bnavn', $searchString, PDO::PARAM_STR);
$stmt->execute();
while ($blogg=$stmt->fetchObject("Blogg"))
{
$bloggArr[]=array('blogg'=>$blogg);
echo $bloggArr['blogg']->hentBnavn();
// sort($bloggArr);
}
$stmt = $this->db->prepare("SELECT * FROM blogger WHERE
fornavn=:fornavn OR etternavn=:etternavn");
$stmt->bindParam('fornavn', $searchString, PDO::PARAM_STR);
$stmt->bindParam('etternavn', $searchString, PDO::PARAM_STR);
$stmt->execute();
while ($blogger = $stmt->fetchObject("Blogger"))
{
$bloggerArr[]= array('blogger' => $blogger);
// sort($bloggArr);
}
$stmt = $this->db->prepare("SELECT * FROM innlegg WHERE tittel=:tittel");
$stmt->bindParam('tittel', $searchString, PDO::PARAM_STR);
$stmt->execute();
while ($innlegg = $stmt->fetchObject("Innlegg"))
{
$innleggArr[] = array('innlegg' => $innlegg);
// sort($innleggArr);
}
$result = array('bloggArr' => $bloggArr, 'bloggerArr' =>
$bloggerArr, 'innleggArr' => $innleggArr);
return $result;
}
I thought I would be able to access the element in the second array by:
echo $resultat['bloggArr']['blogg']->SomeFunction();
the problem is that I get the error message that ['blogg'] is Undefined index. I am been unable to find a way to access the second array elements for a while now, and are wondering if anyone could point me in the right direction. Thanks for all help.
You're not using your arrays properly. Just considering $bloggArr:
$bloggArr[] = array();
creates this:
Array
(
[0] => Array
(
)
)
that line should be changed to:
$bloggArr = array();
To create an empty array. Then, each time through the loop,
$bloggArr[]=array('blogg'=>$blogg);
adds an element like this:
[1] => Array
(
[blogg] => <your object>
)
So, to access those values in the $result array you would need to use a loop:
foreach ($result['bloggArr'] as $blogg) {
echo $blogg['blogg']->SomeFunction();
}
If your queries will only return one result, then you could simply change this line:
$bloggArr[]=array('blogg'=>$blogg);
to
$bloggArr=array('blogg'=>$blogg);
and then you could access the function via
echo $result['bloggArr']['blogg']->SomeFunction();
Related
it's been 3 hours that i'm trying to delete a row in mysql based on a id ...
Seems simple right ?
Taking into consideration that the array might contains several value:
$result = Array ( [3] => 4_Couture )
Array ( [3] => 4_Couture )
$sql_delete = "DELETE FROM users_resumes WHERE id_training_key = ? ";
$stmt_delete= $pdo->prepare($sql_delete);
foreach($result as $r) {
$stmt_delete->execute($r);
}
This seems to be right no ?
error : PDOStatement::execute() expects parameter 1 to be array, string given
Any, any, any clue is very welcome ! thanks a lot from France !
Assuming $result is a one-dimensional array like
$result = [ 3 => '4_Couture' ];
That means you're trying to call $stmt->execute() with a single string value where it requires an array.
I suggest you use bindParam instead
$stmt_delete = $pdo->prepare("DELETE FROM users_resumes WHERE id_training_key = ?");
$stmt_delete->bindParam(1, $r);
foreach ($result as $r) {
$stmt_delete->execute();
}
I want to merge two of my columns (yanlis_cevaplar, cevap_icerik) into an array and this code here gives me only one column in array when I print it (yanlis_cevaplar).
How do I fix it?
$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
$cevap1[] = $row; //grab everything and store inside array
}
$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
$cevap2[] = $row; //grab everything and store inside array
}
$tumcevaplar = array_merge($cevap1, $cevap2);
print_r($tumcevaplar);
Instead of making multiple queries, you can just fetch all the columns you want in one single query:
$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);
print_r($result);
This will result in something like this:
Array
(
[0] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
[1] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
... and so on ..
)
If this isn't what you want, then you need to show us an example.
I also recommend that you go through some basic SQL tutorials. How SELECT works is SQL 101. Here's one of many guides: https://www.tutorialspoint.com/mysql/mysql-select-query.htm
I am trying to get a list of sites ids according to a user id.
This is what I've got so far.
public function getSites() {
$stmt = $this->db->prepare("SELECT Sites_idSites FROM favorites WHERE User_idUser=:idUser");
$userId = $_SESSION['user_session']['idUser'];
$stmt->bindparam(":idUser", $userId);
$stmt->execute();
$siteList = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($siteList as $value) {
foreach($value as $key) {
$stmt = $this->db->prepare("SELECT * FROM sites WHERE idSites=:siteList");
$stmt->bindparam(":siteList", $key);
}
$stmt->execute();
$userSites = $stmt->fetch(PDO::FETCH_ASSOC);
}
return $userSites;
This is the part that I go to "favorites" table and get all the site's ids that correspond to the user id.
$stmt = $this->db->prepare("SELECT Sites_idSites FROM favorites WHERE User_idUser=:idUser");
$userId = $_SESSION['user_session']['idUser'];
$stmt->bindparam(":idUser", $userId);
$stmt->execute();
$siteList = $stmt->fetchAll(PDO::FETCH_ASSOC);
$siteList return as an array like this:
Array
(
[0] => Array
(
[Sites_idSites] => 20
)
[1] => Array
(
[Sites_idSites] => 21
)
[2] => Array
(
[Sites_idSites] => 22
)
)
Now, I want to go to the table where all the sites are and only get the ones with those ids.
This is what I am using, but it only gets the last one:
foreach($siteList as $value) {
foreach($value as $key) {
$stmt = $this->db->prepare("SELECT * FROM sites WHERE idSites=:siteList");
$stmt->bindparam(":siteList", $key);
}
$stmt->execute();
$userSites = $stmt->fetch(PDO::FETCH_ASSOC);
}
If I do print_r($userSites), I will return:
Array
(
[idSites] => 22
[name] => rwrwer
[url] => werwerwerwer
[Category_idCategory] => 1
)
As you can see, it is only returning the last one. How do I make it return an array with all the sites in it? Am I doing something wrong?
I finally fixed it:
public function getSites() {
$stmt = $this->db->prepare("SELECT sites.* FROM favorites INNER JOIN sites ON favorites.Sites_idSites = sites.idSites WHERE favorites.User_idUser = :idUser");
$userId = $_SESSION['user_session']['idUser'];
$stmt->bindparam(":idUser", $userId);
$stmt->execute();
$siteList = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $siteList;
}
This is because you are running the query outside of the inner loop where you bind the values.
foreach($siteList as $value){
foreach($value as $key){
$stmt = $this->db->prepare("SELECT * FROM sites WHERE idSites=:siteList");
$stmt->bindparam(":siteList",$key);
// Bind and rebind, so only the last one "Sticks"
}
// Run the query after the loop
$stmt->execute();
$userSites = $stmt->fetch(PDO::FETCH_ASSOC);
}
You are basically rebinding the :siteList on each iteration. Then when you run it, only the last time you bound it "sticks". Also fetch will only return a single row (at least without looping over it).
You could just move that inside of the loop and then do fetchAll, but a better way is to build a list and then use IN() like this:
foreach($siteList as $value){
$i = 0;
$ids = [];
$where = [];
$sql = 'SELECT * FROM sites WHERE';
foreach($value as $key){
$placeholder = ":id_{$i}";
$where[] = $placeholder;
$ids[$placeholder] = $key;
++$i;
}
$this->db->prepare($sql . ' idSites IN( ' . implode(',', $where) . ' )');
$stmt->execute($ids);
$userSites = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
The SQL should look like this:
SELECT * FROM sites WHERE idSites IN( :id_1,:id_2,:id_3 )
And the $ids array should look like this
$ids = [':id_1'=>1,':id_2'=>53,':id_3'=>1239];
Except, I just made up those numbers (obviously).
This way, you can reduce the number of queries you execute. You may even be able to put it outside of the loop(s) entirely, but without more context I can't really say that. The basic thing is, is that calling the database is expensive and you should endeavor to do so as few times as possible.
I am having trouble updating the values of an multidimensional associative array. The array $people has been generated from another MySQL call. With :
array_push($people, array("forename" => $pat_f_name, "surname" => $pat_s_name,"id" => $id)); I have set $forname and $surname to "", just to have the key there.
I am trying to iterate though the array making an SQL call and retrieve the relevant forename and surname and then update the keys at that index of the array.
Below is my attempt so far.
Thanks in advance.
$stmt = $mysql->stmt_init();
foreach ($people as $person)
{
if($stmt->prepare("SELECT forename,surname FROM worker WHERE id = ?"))
{
$stmt->bind_param('i', $p_id);
$p_id = $person["id"];
$stmt->execute();
$stmt->bind_result($f_name, $s_name);
while($stmt->fetch())
{
$people[$person]["forename"] = $f_name;
$people[$person]["surname"] = $s_name;
}
}
}
$stmt->close();
$person is an array
$p_id = $person["id"];
this
$people[$person]["forename"] = $f_name;
should output:
Warning: Illegal offset type in ....
and
var_dump($people)
output
array(0) { }
better
foreach($people as $key => $person)
<your code>
$people[$key]["forename"] = $f_name;
I think the main problem here is that you try to use $person as index. Either you give your array ($people) a proper index or create a completely new array which you populate with your new $persons in your while-loop.
For the index solution add people to your array like this instead:
$people[$i++] = $person;
For the new array solution, create a new array and then populate it using:
$newPeople[] = $person;
I am building a function that acts like Drupal's variable_initialize() function that pulls all key/value pairs into a global variable. I am trying to find the proper parameters I need to put into fetchAll() to remove the row number and get basically what fetch(PDO::FETCH_ASSOC) does but for all returned rows.
I basically want fetchAll to return:
Array {
[name] = value,
[name2] = value2,
[name3] = value3,
}
The variable table is a simple 2 column table (name)|(value)
function variable_init() {
global $db, $variable;
$query = "SELECT * FROM variable";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(); //need help here
foreach($result as $name => $value) {
$variable[$name] = $value;
}
}
I have tried PDO_COLUMN/PDO_GROUP/etc... but I can't seem to offset the array to remove the row numbers. Thanks.
I think you may be getting confused about what PDOStatement::fetchAll() returns.
The method returns all rows (arrays or objects, depending on fetch style) in an array.
Try this
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$variable[$row['name']] = $row['value'];
}