undefined index in php PDO while statement [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
check when PDO Fetch select statement returns null
(2 answers)
Closed 9 years ago.
I am a beginner with php and PDO and need help solving this error that I keep getting on this line of code
$category_name [$category["category_id"]] = $category["category"]; I continue to get, Notice: Undefined index: category. Also Undefined index: category_id. I dont have a clue as to why, could someone provide me with the correct way to do this. Here is my code. This one slightly different because it used in a while statement.
// get the item category names
$category_name = Array();
$query = 'SELECT * FROM category_2';
$categories_list = $db->prepare($query);
$categories_list->execute();
while ($category = $categories_list->fetchAll())
{
$category_name [$category["category_id"]] = $category["category"];
}

try this:
We will have single array in each time in loop in $category. You can access any database attributes in this array like this: $category['attribute_name']
while ($category = $categories_list->fetch(PDO::FETCH_ASSOC))
{
$category_name [$category["category_id"]] = $category["category"];
}
print_r($category_name);

You're probably looking for fetch(PDO:: FETCH_ASSOC) instead of fetchAll()

Related

Using str_replace in table query in MYSQL [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
If you create a variable inside a if statement is it available outside the if statement?
(4 answers)
How to replace "if" statement with a ternary operator ( ? : )?
(16 answers)
If variable equals value php [duplicate]
(4 answers)
Closed 2 years ago.
There are a lot of examples on SO of using str_replace to modify a query that uses variables in MYSQL but I can't find one that solves my problem.
I have the following legacy query that I'm debugging written in PHP and MySQL.
Somewhat simplified it is:
$sql = "SELECT * from MOVIES WHERE cat = '$cat'";
In the event that cat has a certain value, say, "action" I want to check for "adventure";
Let's say you start with query:
$cat = "action";
$sql = "SELECT * FROM MOVIES WHERE cat='$cat'";
I'm trying to modify the query with:
$needle = "cat=".$cat;
$altcat = "adventure";
$altwhere = "cat=".altcat;
$sql = str_replace($needle,$altwhere,$sql); //NOTHING GETS REPLACED...NOT MATCHING Needle
How can I do this? I'm thinking the problem has something to do with use of spaces or apostrophes in the sql string but can't get it to work.
Thanks for any suggestions.
You want to replace "cat='".$cat."'" with "cat='adventure'", not "cat=".$cat with "cat=adventure".
(Though you are inconsistent in saying if there are spaces around the =.)
But you should not do this and should use a placeholder instead.
I would not try to do string substitution on the SQL query. Instead, just use query parameters.
$cat = 'action'; // suppose this is the input to your program
$sql = "SELECT * from MOVIES WHERE cat = ?";
if ($cat == 'action') {
$cat = 'adventure';
}
$stmt = $db->prepare($sql);
$stmt->execute( [ $cat ] );

Trying to get property of non-object in on line 20 [duplicate]

This question already has answers here:
How to force PDOStatement->fetchAll to return array of objects?
(3 answers)
Closed 3 years ago.
I'm getting an error and I don't really know where is the issue. Please can anybody show me what is wrong? I would appreciate any assistance, thanks!
Trying to get property of non-object in on line 20
class.php
class PostsData extends dbh {
public function fetchAllPosts() {
$sql = "SELECT * FROM post";
$stmt = $this->connect()->query($sql);
$stmt->execute([]);
$result = $stmt->fetchAll();
return $result;
} }
blog.php
$post_ = new PostsData;
$allposts = $post_->fetchAllPosts();
foreach ($allposts as $post) {
echo $post->post_title; //error
You are not checking if the result returned is null or not. The error would be generated if it is because there will be no property to access altogether.
Consider a print statement in FetchAllPosts function to check if you get any rows returned. That may help narrow down the scope of the error.

Why am I getting an undefined variable for only 1 of 6 variables where all the others work? [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 3 years ago.
I have to create 6 queries and print them to an HTML document. 5 out of the 6 variable work perfectly and display the results, I use the same syntax for all 6 variables, but the 4th variable is not working despite checking all the syntax and not having any errors in my IDE. I am getting these two errors in the browser:
Notice: Undefined variable: containsNumbers in C:\xampp\htdocs\scripts\Project3\template.html.php on line 38
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\scripts\Project3\template.html.php on line 38
I've already gone through all the code to make sure all spelling is good and that the syntax matches specifically. I feel like the problem I'm having is with my for each loop.
Here is the php snippet
//Try catch statment with query to check if the first name contains numbers.
try{
$sql = "SELECT * FROM employees WHERE first_name REGEXP '[0-9]' 'results'";
$result = $pdo->query($sql);
} catch (PDOException $e){
$output = "Error selecting id" . $e->getMessage();
include 'output.html.php';
exit();
}
// For each loop used to process results one at a time
foreach ($result as $row){
//Stores each results of the query in an array called containsNum
$containsNumbers[] = $row['results'];
}
And here is the HTML snippet
<h1>Here are the results of any names with numbers in them.</h1>
<div class="wrapper">
<div id="section--4" class="section">
<?php foreach ($containsNumbers as $employee): ?>
<div><?php echo htmlspecialchars($employee, ENT_QUOTES, 'UTF-8');?></div>
<?php endforeach; ?>
</div>
</div>
I expect the result to print any names that have numbers in them, but I am just getting errors.
EDIT****: to add some context this is the question I am trying to answer:
4. Write a query to check if the first_name fields of the employees table contains numbers.
You should initialize the variable to an empty array before the loop. Otherwise, if the query doesn't return any rows, the variable will be undefined.
$containsNumbers = array();
// For each loop used to process results one at a time
foreach ($result as $row){
//Stores each results of the query in an array called containsNum
$containsNumbers[] = $row['results'];
}
Your query also has a syntax error. The string 'results' at the end doesn't belong there. This should have triggered an exception. Are you sure you enabled PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION in your PDO options?
First, it is not clear what you are trying to get when
"SELECT * FROM employees WHERE first_name REGEXP '[0-9]' 'results'"
To me this query itself should fail.
Reading your code down there I suspect you want to alias the column first_name as results.
Secondly, according to php documentation query returns PdoStatement object. That means you need to fetch result from it in kind : fetch, fetchAll, etc.
Here is my final guess this is how your code should look like:
try{
$sql = "SELECT first_name as results FROM employees WHERE first_name REGEXP '[0-9]'";
$result = $pdo->query($sql);
} catch (PDOException $e){
$output = "Error selecting id" . $e->getMessage();
include 'output.html.php';
exit();
}
$containsNumbers = $result->fetchAll(PDO::FETCH_ASSOC);

Trying to get property of non-object in php class [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
enter image description hereI make a one function to fetch the data from database in php.I used the return value of another function for select the id from the database.But when i store worker id into array i get the error "Trying to get property of non-object" like this.What i do?I wan to store match id according to query into one array.
public function getWorkers()
{
$db = JFactory::getDBO();
$orderid=$this->getTodayOrder();
$workersId=array();
foreach($orderid as $workers1)
{
$query2 = "SELECT * FROM #__orderassignment WHERE orderid='".$workers1."'";
$db->setQuery($query2);
$result1 = $db->loadObjectList();
$workersId[]=$workers1->workers;
}
return $workersId;
}
if array is given then you need to access it like this
$workersId[]=$workers1['workers'];

MySQLi Insert Statement placing NULL for variable [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
So I have the following code which is used to add a row to the respondent table, all working except when trying to add the value in of Brand:
$brand = 'Central';
function new_respondent() {
global $link;
$proc = mysqli_prepare($link, "INSERT INTO trespondent (brand, code) VALUES (?, uuid());");
mysqli_stmt_bind_param($proc, "s", $brand);
mysqli_stmt_execute($proc);
$respondent_id = mysqli_insert_id($link);
mysqli_stmt_fetch($proc);
mysqli_stmt_close($proc);
mysqli_clean_connection($link);
}
This code works (to a point) adds a row in the table and adds in the UUID no problems but brand is going in as NULL - I'm trying to work out if I am missing something very obvious here!
Any and all suggestion welcome.
You need to add $brand to your global, since it's outside of the function:
global $link, $brand;
Alternatively, you can modify your function to accept $brand as parameter:
function new_respondent($brand) {
...
}

Categories