Error when using mysql_fetch_array(); - php

table data(id, name)
function getData() {
$data = array();
$sql = 'Select * From data';
$query = mysql_query($sql);
if(!$query) {
echo "Error: " . mysql_error();
exit;
}
while($row = mysql_fetch_array($query)) {
$data[] = $row;
}
return $data;
}
$data = $this->getData();
foreach($data as $dt) {
echo $dt->name;
}
I get an error when I echo $dt->name;, the output is null, How do I fix it ?

$dt is not an object but a array. $dt->name should be $dt['name'].

Try:
var_dump($data);
//if its not a class then simply do
$data = getData();

Related

Trying to get property of non-object CRUD

I am making a CRUD system for blog publications, but it's kinda strange, another developer (with more experience) looked to my coded and for him it's all right too, but this error (Notice: Trying to get property of non-object in C:\xampp\htdocs\genial\painel\inc\database.php on line 32) remains appearing.
My database code:
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
function open_database() {
try {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
return $conn;
} catch (Exception $e) {
echo $e->getMessage();
return null;
}
}
function close_database($conn) {
try {
mysqli_close($conn);
} catch (Exception $e) {
echo $e->getMessage();
}
}
function find( $table = null, $id = null ) {
$database = open_database();
$found = null;
try {
if ($id) {
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_assoc();
}
}
else {
$sql = "SELECT * FROM " . $table;
$result = $database->query($sql);
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
}
} catch (Exception $e) {
$_SESSION['message'] = $e->GetMessage();
$_SESSION['type'] = 'danger';
}
close_database($database);
return $found;
}
function find_all( $table ) {
return find($table);
}
function save($table = null, $data = null) {
$database = open_database();
$columns = null;
$values = null;
//print_r($data);
foreach ($data as $key => $value) {
$columns .= trim($key, "'") . ",";
$values .= "'$value',";
}
$columns = rtrim($columns, ',');
$values = rtrim($values, ',');
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro cadastrado com sucesso.';
$_SESSION['type'] = 'success';
} catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
function update($table = null, $id = 0, $data = null) {
$database = open_database();
$items = null;
foreach ($data as $key => $value) {
$items .= trim($key, "'") . "='$value',";
}
$items = rtrim($items, ',');
$sql = "UPDATE " . $table;
$sql .= " SET $items";
$sql .= " WHERE id=" . $id . ";";
try {
$database->query($sql);
$_SESSION['message'] = 'Registro atualizado com sucesso.';
$_SESSION['type'] = 'success';
}
catch (Exception $e) {
$_SESSION['message'] = 'Nao foi possivel realizar a operacao.';
$_SESSION['type'] = 'danger';
}
close_database($database);
}
Sorry if it's not right idled.
I put an space on the code after the "FROM" at
$sql = "SELECT * FROM" . $table . " WHERE id = " . $id;
The error remains the same but know on line 36 that is:
if ($result->num_rows > 0) {
$found = $result->fetch_all(MYSQLI_ASSOC);
}
Turned the code on line 36 to:
$if (result = $database->query($sql)) {
The error disappeared, others problems not relative to this question happened.
Just in case this question isn't closed as off-topic -> typo generated, I'd better provide an acceptable answer.
Add a space between FROM and $table in your SELECT query.
Check for a non-false result from your query.
Your new code could look like this:
$sql = "SELECT * FROM `$table`";
if ($id) {
// assuming id has been properly sanitized
$sql .= " WHERE id=$id"; // concatenate with WHERE clause when appropriate
}
if ($result = $database->query($sql)) { // only continue if result isn't false
if ($result->num_rows) { // only continue if one or more row
$found = $result->fetch_all(MYSQLI_ASSOC); // fetch all regardless of 1 or more
}
}
$sql = "INSERT INTO " . $table . "($columns)" . " VALUES " ($values);"; has too many double quotes in it -- you can tell by how Stack Overflow highlights the characters. I could say that you could clean up the syntax, but it would ultimately be best to scrap your script and implement prepared statements.

Parsing json array And Merging Objects via php

I Have a json array with id type answer I'm merging id, type and answer together and put them in the id2 column, so why can't I get $answers value in output?
[{"id":"38","answer":[{"option":"3","text":"HIGH"}],"type":"a"},
{"id":"39","answer":[{"option":"3","text":"LOW"}],"type":"b"},
{"id":"40","answer":["Hello Word"],"type":"c"}]
This is my code:
<?php
$con=mysqli_connect("localhost","root","","arrayok");
mysqli_set_charset($con,"utf8");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){
$json = preg_replace("!\r?\n!", "", $json);
$jason_array = json_decode($json,true);
// id2
$id = array();
foreach ($jason_array as $data) {
if (array_key_exists('id', $data)) {
if (array_key_exists('type', $data)) {
if (array_key_exists('answer', $data)) {
foreach($data['answer'] as $ans){
$answers[] = isset($ans['text']) ? $ans['text'] : $ans;
}
$id[] = ' ID='.$data['id'].', TYPE='.$data['type'].', AWNSER='.$answers;
}
}
}
}
// lets check first your $types variable has value or not?
$ids= implode(',',$id); /// implode yes if you got values
$sql1="update user_survey_start set id2='$ids' where us_id=".$row[1];//run update sql
echo $sql1."<br>";
mysqli_query($con,$sql1);
}
}
}
mysqli_close($con);
?>
And this is my output:
update user_survey_start set id2=' ID=38, TYPE=a, AWNSER=Array,
and I got Notice: Array to string conversion in C:\wamp64\www\json\awnser.php on line 29
I want to have value of $answers
Solved By Myself
Because I Couldn't Put Awnser Directly To id[], I Taked Awnser Like This:
$id[] = ' ID='.$data['id'].', TYPE='.$data['type'];
$id[] = isset($ans['text']) ? ' AWNSER='.$ans['text'] : ' AWNSER='.$ans;
And This is My Code:
<?php
$con=mysqli_connect("localhost","root","","arrayok");
mysqli_set_charset($con,"utf8");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){
$json = preg_replace("!\r?\n!", "", $json);
$jason_array = json_decode($json,true);
// id2
$id = array();
foreach ($jason_array as $data) {
if (array_key_exists('id', $data)) {
if (array_key_exists('type', $data)) {
if (array_key_exists('answer', $data)) {
foreach($data['answer'] as $ans){
$id[] = ' ID='.$data['id'].', TYPE='.$data['type'];
$id[] = isset($ans['text']) ? ' AWNSER='.$ans['text'] : ' AWNSER='.$ans;
}
}
}
}
}
// lets check first your $types variable has value or not?
$ids= implode(',',$id); /// implode yes if you got values
$sql1="update user_survey_start set id2='$ids' where us_id=".$row[1];//run update sql
echo $sql1."<br>";
mysqli_query($con,$sql1);
}
}
}
mysqli_close($con);
?>

Form json using php json_encode failed

By using below code
$data = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['title'] = $row['title'];
$data['name'] = $row['name'];
}
}
echo json_encode($data);
I got 1 result, I can get full result if I do $data[] = $row['title'], but I want to make the result like this
{'title' : ['title 1','title 2'], 'name':['John','Amy']}
You are overwriting the title in each loop iteration. You need to accumulate all the titles and then set it in your data array.
$data = array();
$sql = "SELECT title FROM mainlist";
$result = $db->query($sql);
$titles = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
}
}
$data['title'] = $titles;
echo json_encode($data);
The easiest away is probably this:
$rows = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
echo json_encode($rows);
you could achieve by using group_concat on each of the columns in your query. That way you do not need to loop the result again and add column etc...
$sql = "SELECT group_concat(title) as title,group_concat(name) as name FROM list";
$result = $db->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Try this:
$titles = array();
$names = array();
$sql = "SELECT title,name FROM mainlist";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
$names[] = $row['name'];
}
}
echo json_encode(array("title" => $titles, "name" => $names));
UPDATE
Updated my code to let you manage an undefined number of columns as result
$out = array();
$sql = "SELECT * FROM wp_cineteca";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$keys = array_keys($row);
for ($i = 0; $i < count($row); $i++) {
$out[$keys[$i]][] = $row[$i];
}
}
}
echo json_encode($out);

Replace string at particular position in function In PHP?

I want to Print some dynamically data from my function to passing string in function like this.
My Function
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
$newtempelt = str_replace("Eval", '$row', $itemtemplet);
while ($row = mysql_fetch_array($result))
{
echo $newtempelt;
}
}
}
Passing Value In Function
<ul>
<?php
$rptvalue="<li><a href=''>Eval['name']</a></li>";
$myFun->mysql_funX_Repeter("Select name from tbldemo",$rptvalue);
?>
</ul>
My Output
$row['name']
$row['name']
$row['name']
I want Output
raj
ram
prince
But it's Show me only variable but not show it's database value.
How to solve this...!!!
I would change a little bit your method.
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
while ($row = mysql_fetch_array($result))
{
echo "<li><a href=''>".$row[$itemtemplet]."</a></li>";
}
}
}
And of course, your method invokation:
<ul>
<?php
$rptvalue="name";
$myFun->mysql_funX_Repeter("Select ".$rptvalue." from tbldemo",$rptvalue);
?>
</ul>
And that's how I'd do it to avoid nasty evals. :)
function mysql_funX_Repeter($query,$itemtemplet)
{
$html='';
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
$num_rows=mysql_num_rows($result);
if($num_rows){
while ($row = mysql_fetch_array($result))
{
$newtempelt = str_replace("Eval", $row['column_name'], $itemtemplet);
$html.="<li><a href=''>".$newtempelt."</a></li>";
}
}
return $html;
}
//calling method mysql_funX_Repeter
<ul>
<?php
$rptvalue="name";
echo $myFun->mysql_funX_Repeter("Select ".$rptvalue." from tbldemo",$rptvalue);
?>
</ul>
Developer My Problem Was Solved.
Thanks for Reply.
My Function
//This Repeter Function Created By Priyank Patel
function mysql_funX_Repeter($query,$itemtemplet)
{
$this->mysql_funX_connect();
$result = mysql_query($query) or die("Repeter Query Error.");
if (!$result)
{
$message = 'ERROR:' . mysql_error();
return $message;
}
else
{
preg_match_all('/{([^}]*)}/', $itemtemplet, $matches);
$select = '';
while($row = mysql_fetch_assoc($result)){
$aux = $itemtemplet;
for($i = 0; $i < count($matches[0]); $i++){
$aux = str_replace($matches[0][$i], $row[$matches[1][$i]],$aux);
}
$select .= $aux."\n";
}
mysql_close();
return $select;
}
}
Calling Style
<ul><?php $templet="<li>{name}</li>";echo $myFun->mysql_funX_Repeter("Select * from tbldemo",$templet);?></ul>

php oci_fetch_array and pass value to function issue

1) I want to save case 1 value to an array. Return this array and pass it to a function. The code become case 2, but no result come out, where is the problem?
2) In function display_urls, i want to echo both $url and $category. What should i do in IF condition or add another line of code?
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url."";
echo "".$category."";
}
}
echo "";
}
case 1: work fine
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$i=0;
echo "";
while( $row = oci_fetch_array($result) ){
$i++;
echo "";
echo "".$row['USERNAME']."";
echo "".$row['BM_URL']."";
echo "".$row['CATEGORY']."";
echo "";
}
echo "";
case 2:
$url_array = array();
while( $row2 = oci_fetch_array($result, OCI_BOTH)){
$i++;
$url_array[$count] = $row[0];
}
return $url_array;
I think you probably want something like this:
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url['BM_URL']."";
echo "".$url['CATEGORY']."";
}
}
echo "";
}
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$url_array = array();
while( $row = oci_fetch_array($result, OCI_ASSOC)){
$url_array[] = $row;
}
display_urls($url_array);
This will store all the information on the URLs in $url_array with a lookup by column name.

Categories