Table Structure:
user table:
id:int
user:varchar
hash:varchar
realm:int
Game Table:
ID:int:auto
Game:varchar
Password:varchar
Difficulty:tinytext
Realm:tinytext
Empty:int
timestamp:int
Player Table:
ID:Int
GameID:INT
Name:varchar
timestamp:int
When im trying to fetch_assoc() i'm getting error:
Call to a member function fetch_assoc() on a non-object
function RequestToRemove($Hash, $timestamp)
{
include "conf.php";
$conn = new mysqli($serverip, $username, $password, $dbname, $Port);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$hash = mysqli_escape_string($conn, $Hash);
$UserQuerry = "SELECT * from User where hash = '$hash'";
$UserResult = $conn->query($UserQuerry);
if (!$UserResult) {
echo "hash not found: ".$hash;
}
if ($UserResult->num_rows > 0)
{
while($UserRow = $resulti->fetch_assoc())
{
$PlayerQuerry = "SELECT * from Players where ID = '".$UserRow['id']."'";
$PlayerResult = $conn->query($PlayerQuerry);
while($PlayerRow = $PlayerResult->fetch_assoc())
{
$gameID = $PlayerRow['GameID'];
$gameQuerry = "SELECT * from games where ID = '$gameID'";
$gameResult = $conn->query($gameQuerry);
if ($gameResult->num_rows > 0)
{
while($GameRow = $gameResult->fetch_assoc())
{
if((int)$GameRow['timestamp'] <= ($timestamp - 30) && (int)$GameRow['Empty'] == 1)
{
$gameDeleteQuerry = "DELETE FROM games where id = '".$gameID."'";
$conn->query($gameDeleteQuerry);
echo "Game Updated";
}
}
$playerDeleteQuerry = "DELETE FROM Players where id = '$gameID'";
$gamesUpdateQuerry = "UPDATE games SET timestamp='$timestamp' where ID = '$gameID'";
$gamesUpdateResult = $conn->query($gamesUpdateQuerry);
if (!$gamesUpdateResult) {
echo "Can't UPDATE game! ID: $gameID Error: ". $conn->error;
return;
}
$conn->query($playerDeleteQuerry);
$PlayerQuerry = "SELECT * from players where GameID = '$gameID'";
$PlayerResult = $conn->query($PlayerQuerry);
if (!$PlayerResult) {
echo "Can't get players! Error: " . $conn->Error;
return;
}
if ($PlayerResult->num_rows <= 0) {
$gameUpdateEmptyQuerry = "UPDATE games SET Empty='1' where GameID = '".$gameID."'";
$conn->query($gameUpdateEmptyQuerry);
}
} else {
echo "0 results";
}
}
}
}
$conn->close();
}
but when im running
SELECT * from User where hash = 'ae3cb232b5e489050bfed7ed984eb04c'
in HeidiSQL
i will get one row in response but i can't still fetch_assoc() in php
Reason for edit: Show full function, requested
you are reassigning a different value to $resulti within the loop:
$sqll = "DELETE FROM Players where id = '$gameID'";
$sqlu = "UPDATE games SET timestamp='$timestamp' where ID = '$gameID'";
$resulti = $conn->query($sqlu);
the mysqli::query() function is tricky, it can return different type of return values - an update statement returns either true or false, whereas a select statement returns a mysqli_result or false.
(and yes, it may help to name the variables a bit more descriptive ;) )
Related
I have over 40'000 entries and each is assigned to a "list_name"
I am basically trying to get just the list_name value echo'd out
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
$groupr = mysqli_fetch_assoc($groupq);
do {
echo $groupr['list_name'];
} while($groupr = mysqli_fetch_assoc($groupq));
however its only displaying 1 entry then no more ..
https://imgur.com/a/3rnXGet
Try this.
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
while($groupr = mysqli_fetch_assoc($groupq)){
echo $groupr['list_name'];
}
$database = "sample" //replace your database name here
$conn=new mysqli("localhost","root","",$database); // here username is root and password is null , change it according to yours
if($conn->connect_error)
{
echo $conn->connect_error;
die("sorry database connection failed");
}
$sql = "SELECT * FROM products-full GROUP BY list_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row['list_name'];
}
}
thats it
try this
$groupq = mysqli_query($dbc, "SELECT list_name, count(*) FROM `products-full` GROUP BY
`list_name`");
while($groupr = mysqli_fetch_assoc($groupq)) {
echo $groupr['list_name'];
}
Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
This code is not working although it's correct
I am using object oriented php.
$this->id is a variable passed by link from another page.
When I run the code it tells me it was successful but that there are zero affected rows.
The one line above is part of the following code:
<?php
class edit {
private $status;
private $remain;
private $cost;
private $id;
public function edit_data() {
$this->status = strtoupper(strip_tags($_POST['status']));
$this->remain = strip_tags($_POST['remain']);
$this->cost = strip_tags($_POST['cost']);
$submit = $_POST['submit'];
$this->id = $_GET['edit'];
$con = mysql_connect("localhost","root","")
or die("Failed to connect to the server: " . mysql_error());
mysql_select_db("Users")
or die("Failed to connect to the database: " . mysql_error());
if($submit) {
if($this->status and $this->remain and $this->cost) {
$sql = "UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
$query = mysql_query($sql,$con);
if(!$query) {
echo("Could not update data: " . mysql_error());
}
echo "<h4>Customer reservation data has been updated successfully.</h4>";
echo "Number of affected rows: " . mysql_affected_rows();
}
else {
echo "Please fill in all fields.";
}
}
mysql_close($con);
}
}
$edit = new edit();
echo $edit->edit_data();
?>
Are you sure about your concatenation?
$sql = "UPDATE reservations SET status = '$this->status',remaining_time ='$this->remain',cost = '$this->cost' WHERE id = '$this->id'";
Print $sql to see the value.
If your database is already updated, you will receive 0 affected lines.
I am not totally sure but try this,
"UPDATE reservations SET status = '".$this->status."',remaining_time ='".$this->remain."',cost = '".$this->cost."' WHERE id = '".$this->id."'";
It seems that your table doesn't contain a value which satisfies where condition.
You can check this by executing a simple query.
$sql = "select * from reservations where id='$this->id'";
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)
Here is my code:
$result = mysqli_query($dbconnection, Data::followUser($user_id, $followUser_id));
$result returns empty here.
followUser method in class Data
public static function followUser($user_id, $followUser_id) {
global $database;
$query = "
SELECT *
FROM profile_follow
WHERE user_id = '{$user_id}'
AND follow_id = '{$followUser_id}';";
$result = $database -> query($query);
$num = mysqli_num_rows($result);
if ($num < 1) {
$toast = "Follow";
$query = "
INSERT INTO profile_follow (user_id, follow_id)
VALUES ('{$user_id}', '{$followUser_id}');";
$result = $database -> query($query);
} elseif ($num > 0) {
$toast = "Unfollow";
$query = "
DELETE FROM profile_follow
WHERE user_id = '{$user_id}'
AND follow_id = '{$followUser_id}';";
$result = $database -> query($query);
}
return $toast;
}
I have verified the function works correctly in echoing out $toast. It is either Follow or Unfollow based on condition. I don't think I am handling it right when it comes out?
Supplemental:
Here is what I am doing with $result:
if ($result == "Follow") {
$output["result"] = "Follow";
echo json_encode($output);
} elseif ($result == "Unfollow") {
$output["result"] = "Unfollow";
echo json_encode($output);
}
What does this all accomplish? You've basically got:
mysqli_query($dbconnection, 'Unfollow');
which is NOT a valid query in any way. $result is NOT empty. It's a boolean false, indicating a failed query...