So I want to make a function where I can fetch data like the following
$user->userData('username');
Here is my current function
public function userData() {
$username = "username";
$query = $this->db->prepare("SELECT * FROM users WHERE username=:username");
$query->execute(['username' => $username]);
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row;
}
the problem is that It's returning this error when I call the function:
Notice: Array to string conversion in /Applications/XAMPP/xamppfiles/htdocs/php/home.php on line 9 Arrays
Line 9 is
echo $user->userData('username');
echo function prints strings.
Array returned by your function is not a string (definitely).
So, php tries to convert array to string and warns you about it.
If you want to print values that are not string - use printr_r or var_dump.
Related
This question already has answers here:
Invalid argument supplied for foreach()
(20 answers)
Closed 1 year ago.
I have had problema with "foreach"...
<?php
/*** user ***/
$sql = "SELECT * FROM user WHERE user_login = '$login' ";
$users = selecionar($sql);
foreach($users as $user) {
$userId = $user['user_id'];
}
?>
<?php
$sqll = "SELECT * FROM cadastro WHERE user_id = '$userId' ";
$cadastro = selecionar($sqll);
foreach($cadastro as $cad) { ?> /* Line 41 */
..... HTML
<?php } ?>
If I register something in PhpMyAdmin this code shows the register. But if there's not register in DB the page shows
Warning: Invalid argument supplied for foreach() in C:\wamp64\www\banheiromovel\02-listagem\listagem_perfil.php on line 41
It looks like selecionar() returns something that isn't iterable if there are no results, like maybe null or false. (Remember that if your function doesn't reach a return statement it's going to return null.)
I think your two best options are either
Wrap the foreach in a conditional to make sure it's not empty before you try to iterate it
if ($users) {
foreach($users as $user) {
$userId = $user['user_id'];
}
}
Modify selecionar() so that it always returns an array, but just returns an empty array if the query returns no results.
I prefer the second one, personally. You can do this by initializing whatever variable you're fetching your query results into in the function to an empty array, then returning that variable after you (possibly) fill it with data.
Like this:
function selecionar(string $sql): array
{
$result = [];
// code that executes a query and fetches results,
// adding the rows to $result if there are any
return $result;
}
Also, you should be executing those queries using prepared statements. Inserting input into the SQL string like that is not safe.
Try the following
/*** user ***/
$sql = "SELECT * FROM user WHERE user_login = '$login' ";
$users = selecionar($sql);
if ($users) {
foreach(array($users) as $user) {
$userId = $user['user_id'];
}
}
?>
I had the same problem and i resolved by adding an array() .
I am trying to search product from the database and then display in view. But it showing me an error that is this...
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_active_rec.php
Line Number: 679
Here is the code of Controller
function search_prd()
{
$query = $this->input->post();
$this->load->model('prd/addprd');
$prd_search = $this->addprd->prd_search($query);
$this->load->view('prd_search', ['prd_search' => $prd_search]);
}
And this code is MODEL
function prd_search($query)
{
$q = $this->db->from('purchase')
->like('item_name', $query)
->get();
return $q->num_rows();
}
CI's input->post() is an array containing POST data. The second parameter of CI's active record like() expects a string. If you mean to pass an individual field value, you will need to access that index:
<input name="search_value">
$query = $this->input->post('search_value'); //notate the field being used here
Then you can query where like:
$this->db->like('column', $query); //query is now a string
Alternatively, if you mean to pass the entire array, you can use where_in()
$this->db->where_in('column', $query); //if you assign $query to $this->input->post();
Before I ask my question, I will post the code: (Please note if you can just explain the second question it'll be sufficient, I am just really confused what's happening at the foreach loop.
<?php
class dbh {
private $servername; private $username; private $password; private $
dbname;
protected function connect() {
$this->servername = "localhost";
$this->username = "root";
$this->password = "";
$this->dbname = "whatever";
$conn = new mysqli($this->servername, $this->username, $this->password,
$this->dbname);
return $conn;
}
}
<?php
class User extends Dbh {
protected function getAllUsers() {
$sql = "SELECT * FROM user";
$result = $this->connect()->query($sql);
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result ->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
}
}
<?php
class ViewUser extends User {
public function showAllUsers() {
$datas = $this->getAllUsers();
foreach ($datas as $data) {
echo $data['uid'] . "<br>";
echo $data['pwd'] . "<br>";
}
}
}
<?php
includes all those classes
?>
<body>
<?php
$users = new ViewUser();
$users->showAllUsers();
?>
</body>
I don't understand a couple things about this code.
Firstly, what is "this" in those classes? It is just a placeholder for the users object, which is the current object, right? I think it is.
Secondly, and my main question, when we call the member function showAllUsers(), we go to the ViewUser class, and then we have a $datas variable that gets assigned to $this->getAllUsers() which ends up returning a $data array, which contains all the rows in the database... Right?
Then my question is, what are the contents of $datas in the foreach loop? Is it an array of rows? $data is supposed to be key values, but $data is also an array which has me very confused.
I am visualizing it like $datas = $data, so
$datas[] = [$data[0], $data[1], $data[2], $data[3], ... $data[last_one]]
and each one of these elements contains a row ...
So foreach($datas as data) goes through each element, but to display it we need to echo data[0]?
Is my understanding correct? I know it's an associative array so those 0, 1, 2... etc are the column titles of table..
Also, what exactly does $fetch_assoc do when we have $row = fetch_assoc? Are we just storing rows in the $rows variable? The while loop is false when we reach the last row, right? I'm just so used to seeing a conditional in a while loop, like for instance while (x == 4). I have never seen a situation where we assign a variable, like for example while (x = 4) until now.
This is actually quite poor for a class handling scheme, but your questions are still valid.
You're sort of right. $this is a reference to the current instance (read: object) of the class where you define a method that uses the this keyword.
Correct in all cases. You're also right in that datas is an array of arrays (which represents the rows in the database table). Each element of $datas contains another array that represents a single row where each element is a column of that row. They're associative arrays so the index is a key, like you said.
As per the documentation, mysqli::query returns an object of type mysqli_result, so you can't access it directly as an array. mysqli::fetch_assoc will convert the mysqli_result into an associative array, row by row by moving a pointer, which is why you keep looping in the while loop until fetch_assoc returns false (that is, when no more rows are in the result object, or when the pointer reaches the last row).
Can anyone explain why the property of the $json object works in the database query when first assigned to a local variable, but throws a string conversion error if used directly? Thanks!
<?php
class Order {
protected $json;
public function __construct($json) {
$this->json = $json;
}
public function createOrder() {
$email = $this->json->email;
//Works
$sql = "INSERT INTO orders SET email='$email'";
// Doesn't work -- Object of class stdClass could not be converted to string
$sql = "INSERT INTO orders SET email='$this->json->email'";
...
}
}
?>
Two problems:
a) PHP's stdClass has no magic __toString() method, so there's no way for a stdClass to be used inside a string.
b) PHP's "-quoted string parser isn't greedy, so your
$sql = "INSERT INTO orders SET email='$this->json->email'";
is parsed/executed as the equivalent of:
$sql = "INSERT INTO orders SET email='" . $this->json . "->email'";
which is where your error message is coming from. $this->json is an object, with no __toString() magic method, therefore the warning.
If you want to use a multi-dimensional object in a "-quoted string, you have to use the {}-extended string syntax:
$sql = "INSERT INTO orders SET email='{$this->json->email}'";
^------------------^
which forces PHP to treat everything inside the {} as a single unit.
The same holds for arrays:
$foo[1][2] = 3;
echo "$foo[1][2]";
is executed as:
echo $foo[1] . "[2]";
and gives you
Array[2]
as the output - arrays in string context are the literal word "Array". Using {} makes it work as expected:
echo "{$foo[1][2]}";
outputs 3.
This is a function to return the username of logged users. However, I can't seem to troubleshoot what's going on and why I'm getting Notice: Array to string conversion in.. on the first if() statement.
function getuserfield($field, $link) {
$query = $link->prepare("SELECT `$field` FROM `users` WHERE `id`= :session_id");
if ($query->execute(array(':session_id' => $_SESSION['user_id']))) {
if ($query_result = $query->fetchAll(PDO::FETCH_ASSOC)) {
return $query_result;
}
}
}
As well as that, the whole page becomes unreadable (in terms of encoding). Naturally, I'd use it like so:
echo "<p>Greetings, you are logged in as:" . getuserfield('username', $link) . "</p>";
The Notice: Array to string conversion indicates that $_SESSION['user_id] is an array which I'm trying to access as a string.
$query->execute(array(':session_id' => $_SESSION['user_id']['id']))
Fixes this. Then calling the function with two foreach() statements.