I have to make a web app that gets information from my database, that gets its info from an API). Then I have to show items under certain conditions.
But when I try to add the data from the API, I got a strange message:
Notice: Trying to get property of non-object in c:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Here is my PHP code:
<?php
require_once 'settings.php';
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_database);
if (mysqli_connect_error()) {
echo mysqli_connect_error($mysqli) . "We are not able to connect to the online database";
}
jsondecode($mysqli);
if (isset($_GET['club']) && !empty($_GET['club'])) {
jsondecode($mysqli);
} else if (isset($_GET['thuisPoint']) && !empty($_GET['thuisPoint']) && ($_GET['uitPoint']) && ($_GET['uitPoint'])) {
updatePoints($mysqli);
} else {
getWedstrijd($mysqli);
}
function jsondecode($mysqli) {
$apiLink = 'http://docent.cmi.hr.nl/moora/imp03/api/wedstrijden?club=';
// $club = $_GET['club'];
$data = json_decode(file_get_contents($apiLink . "Ajax"));
foreach ($data->data as $info) {
$thuisClub = $info->homeClub;
$uitClub = $info->awayClub;
addWestrijden($mysqli, $thuisClub, $uitClub);
}
}
//querys
function addWestrijden($mysqli, $thuisClub, $uitClub) {
$query = "INSERT INTO wedstrijd VALUES(null, '$thuisClub', '$uitClub')";
$resultAddWedstrijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
function getWedstrijd($mysqli) {
$query = "SELECT * FROM wedstrijd ORDER BY thuisClub DESC";
$resultGetWedstijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
while ($result = mysqli_fetch_assoc($resultGetWedstijd)) {
$rows [] = $result;
}
header("Content-Type: application/json");
echo json_encode($rows);
exit;
}
function updatePoints($mysqli) {
$id = $_GET['id'];
$thuisPoints = $_GET['thuisPoint'];
$uitPoints = $_GET['uitPoint'];
$query = "UPDATE wedstrijd "
. "SET thuisPunt = '$thuisPoints', uitPunt = '$uitPoints') "
. "WHERE id = '$id'";
mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
I did modify it a bit so it would add data from the API. I really would appreciate it if someone could help me.
Change your foreach to:
foreach ($data as $data => $info)
Related
I'm having some problems when returning a large number of rows from SQL Server using PHP + Datatables. My code is using one main loop then some "subloops".
Sometimes, when the number of lines gets up to 1000+ the execution is aborted and the error MSSQL: SQLSTATE[] (null) (severity 0) is shown.
Connection function:
function pdo_mssql($sql){
$host = ***;
$user = ***;
$pass = ***;
$db = ***;
try {
$PDO = new PDO( 'dblib:host=' . $host . ';dbname=' . $db, $user, $pass );;
}
catch ( PDOException $e ) {
echo 'MSSQL error: ' . $e->getMessage(); exit;
}
$result = $PDO->query( $sql );
if (is_array($result)){
$row = $result->fetchAll( PDO::FETCH_ASSOC );
}else{
$row = $result;
}
return $row;
}
Example of the script where the error occurs:
$sql = "SELECT ....";
$return = pdo_mssql($sql);
foreach ($return as $row){
$sql2 = "SELECT ...."
$return2 = pdomssql($sql2);
foreach ($return2 as $row2){
// Do something
}
$sql2 = "SELECT ...."
$return2 = pdomssql($sql2);
foreach ($return2 as $row2){
// Do something
}
$sql2 = "SELECT ...."
$return2 = pdomssql($sql2);
foreach ($return2 as $row2){
// Do something
}
// Show results
}
Does anyone have any suggestion to fix it?
Thanks
Please check the code, $return2 is not being assigned in inner loop. May be you want to do
$sql2 = "SELECT ...."
$return2 = pdomssql($sql2);
i am trying to get this output from a database of countries. i had use the mysqli_fetch_object() function but it does not work with me
"countries":[{"countryname":"India","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/india.png","language":"Hindi","capital":"New Delhi","currency":{"code":"INR","currencyname":"Rupee"}},{"countryname":"Pakistan","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/pakistan.png","language":"Urdu","capital":"Islamabad","currency":{"code":"PKR","currencyname":"Pakistani Rupee"}}]}
and i am use this php script
<?php
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
{
die ("Erro in connection" . mysqli_connect_error);
}
else{ $encode = array();
$sql="select * from country ";
$res=mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
//$temp_array[]=$row;
$encode=$row;
}
//echo json_encode($temp_array);
echo json_encode($encode);
}
else
{
echo " 0 Rows";
}
}
?>
if anybody can help me ?
Your code should be something like below;
<?PHP
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
die ("Error in connection" . mysqli_connect_error);
else{
$encode = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
$encode[]=$row;
}
}
echo json_encode($encode);
}
?>
You do not need to write down 0 rows because you are returning a json object which has an array so when you check result.length it tells you the row count.
As an advice you may use something like below;
<?php
require 'config.php';
$con = mysqli_connect($servername,$username,$password,$db);
$resultArray = array();
$resultArray["error"] = true; //That will tell your javascript client if any error exits.
$resultArray["errorMessage"] = ""; //We will set this value if any error exits;
if(!$con)
{
$resultArray["error"] = true;
$resultArray["errorMessage"] = "Error in connection" . mysqli_connect_error();
}
else{
$resultArray["error"] = false;
$itemCollection = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
while($row = mysqli_fetch_object($res))
$itemCollection[]=$row;
$resultArray["itemCollection"] = $itemCollection;
}
echo json_encode($resultArray);
?>
In my sample you are going to get a json result something like below;
{"error":true,"errorMessage":"ErrorMessageIfExists","itemCollection":[yourObject,yourObject]}
Hope this helps you.
I have a problem switching from MYSQL to MYSQLi. The codes work fine with MYSQL but when i change the connection to MYSQLi, I received the error as stated above when I'm fetching my query. How can i fetch my queries using mysqli functions?
Code:
function __construct(){
$this->link = mysqli_connect('localhost', 'root', '', 'ajax_rating');
if (!$this->link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($this->link) . "\n";
}
function getItems($id = null){
if(isset($_GET['id']))
{
$query = $this->link->query("SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = $this->link->query("SELECT * FROM items");
}
$rowCount = $query->rowCount();
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
Use num_rows
Read MySQLi row_count
So final answer would be
function getItems($id = null)
{
if(isset($_GET['id']))
{
$query = $this->link->query("SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = $this->link->query("SELECT * FROM items");
}
$rowCount = $query->num_rows;//change here
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
}
EDIT 01
use mysqli_fetch_all instead of fetchAll()
mysqli_fetch_all($query,MYSQLI_ASSOC);
so answer world be
if($rowCount >= 1)
{
$result = mysqli_fetch_all($query,MYSQLI_ASSOC);
}
you can use num_rows for counting rows in DB and you can direct call connection like this :-
//for connection
$con = mysqli_connect("localhost", "root", "", "ajax_rating");
if(!$con)
{
echo "connection error";
}
//query
function getItems($id = null)
{
if(isset($_GET['id']))
{
$query = mysqli_query($con,"SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = mysqli_query($con,"SELECT * FROM items");
}
if (mysqli_num_rows($query) > 0)//change here
{
while($row = mysqli_fetch_assoc($query))
{
$result=$row;
}
}
else
{
$result = 0;
}
return $result;
}
I am getting this error on only some browsers and I am not sure why. I am hoping this is a simple fix. It sounds like it should be. Here is the error and below that is the code.
warning : mysqli_fetch_array expects parameters 1 to mysqli_result, boolean given in /home/content/yada/html/myapp/main.php on line 71
By the way, this is line 71:
while($row = mysqli_fetch_array($result))
and below is the full code
$type = $_POST[type];
$user="theUser";
$password="thePassword";
$database="theDatabase";
$TABLE = "user";
#mysql_connect("mydb.com",$user,$password);
#mysql_select_db($database) or die("Unable to select database");
if($_POST[type]) {
$query = "UPDATE $TABLE
SET type = $type
WHERE fbId = $id";
if(mysql_query($query)) {
//echo "Settings saved successfully!";
} else {
echo ("MySQL Error: ".mysql_error());
}
}
$con=mysqli_connect('localhost',"$user","$password","$database");
// Check connection
if(mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM $TABLE WHERE fbID = $id");
while($row = mysqli_fetch_array($result)) {
$currentType = $row['type'];
//echo $currentType;
}
if ($result = mysqli_query($con, "SELECT * FROM $TABLE WHERE fbID = $id", MYSQLI_USE_RESULT)) {
//echo "True";
//mysqli_free_result($result);
}
Use
echo mysqli_error($con);
to show the error MySQL server gives when executing the SQL query on line 71. This will reveal what is wrong with the query.
Warning:mysql_fetch_array(): supplied argument is not a valid MySQL result resource in **/home/davzyco1/public_html/notes/functions.php** on line 43
was the error I got when I use the below class, even though the class works PERFECTLY with my old webhost. Here's my new hosts php info: http://davzy.com/notes/php.php
class mysqlDb
{
public $con;
public $debug;
function __construct($host,$username,$password,$database)
{
$this->con = mysql_connect($host,$username,$password);
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $this->con);
}
function kill()
{
mysql_close($this->con);
}
function debugOn()
{
$this->debug = true;
}
function debugOff()
{
$this->debug = false;
}
function select($query,&$array)
{
$c = 0;
$result = mysql_query("SELECT ".$query);
if($this->debug == true)
echo "SELECT ".$query;
while($row = mysql_fetch_array($result))
{
foreach($row as $id => $value)
{
$array[$c][$id] = $value;
}
$c++;
}
}
function update($update, $where,$array)
{
foreach($array as $id => $value)
{
mysql_query("UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}");
if($this->debug == true)
echo "UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}<br><br>";
}
}
function updateModern($update, $where,$array)
{
foreach($array as $id => $value)
{
mysql_query("UPDATE {$update} SET `{$id}` = '{$value}'
WHERE {$where}");
if($this->debug == true)
echo "UPDATE {$update} SET {$id} = '{$value}'
WHERE {$where}<br>";
}
}
function delete($t, $w)
{
mysql_query("DELETE FROM `{$t}` WHERE {$w}");
if($this->debug == true)
echo "DELETE FROM `{$t}` WHERE {$w}<br><br>";
}
function insert($where, $array)
{
$sql = "INSERT INTO `{$where}` (";
$sql2 = " VALUES (";
foreach($array as $id => $value){
$sql .= "`{$id}`, ";
$sql2 .= "'{$value}', ";
}
mysql_query(str_replace(', )',')',$sql.")") . str_replace(', )',')',$sql2.");"));
if($this->debug == true)
echo str_replace(', )',')',$sql.")") . str_replace(', )',')',$sql2.");")."<br><br>";
}
}
This is because mysql_query() will return FALSE if an error occured, instead of returning a result resource. You can check the error by calling mysql_error(), as shown here:
function select($query,&$array)
{
$c = 0;
$result = mysql_query("SELECT ".$query);
if($this->debug == true)
echo "SELECT ".$query;
if (!$result) {
// an error occured, let's see what it was
die(mysql_error());
}
while($row = mysql_fetch_array($result))
{
foreach($row as $id => $value)
{
$array[$c][$id] = $value;
}
$c++;
}
}
Based on the error message, you can find out what the real problem is.
You should really test to see if $result is not false before using it with mysql_fetch_array. The error you're receiving is indicative that the query itself failed.
Have you configured your database with your new host? (do all the tables exist?)
As Mark said above, you really should check your result before trying mysql_fetch_array on a result set, and verify that all tables actually exist.
Without knowing how your original server was set up, I can only guess, but it may also be that your old server was set up to not display warnings.