PHP infinite loop issue - php

I can get the correct code to work, but i want to be able to use objects and methods, which doesn't work. The same entry in the database is repeated until the query crashes. I saw other people that had queries inside of the while statement, but i thought that the method i am using should only query the statement once, but im likely wrong. Thanks.
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>
Seperate class
public function __construct(){
$this->con = mysqli_connect("localhost","root","pass","Minecraft");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getUUID($username) {
$result = mysqli_query($this->con,"SELECT UUID FROM loginLogger WHERE Username='" . $username . "'");
return mysqli_fetch_array($result)[0];
}
public function getReports($username) {
$result = mysqli_query($this->con,"SELECT * FROM reportLogger WHERE UUID='" . $this->getUUID($username) . "'");
return $result;
}

Each time you call while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) you are making a new query, so it's fetching the samething over and over again.
a solution could be:
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
$store = $MySQL->getReports('jackginger');
while($row = mysqli_fetch_array($store)) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>

Related

Php MySQL into json - trying to put query into function

I'm trying to build a very basic API, I've got a query that pulls data from a MySQL view, I can echo the query out as json no problem but I want to put the query in a function in order to be able to call it from the API script...I'm just having some trouble putting the code into a function.
Here's the ode that works.....
<?php
$servername = "database.com";
$username = "username";
$password = "password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["year"]. " - " . $row["Month"]. " " . $row["the_days"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
...and this is my attempt to put it into a function (that doesn't work!)...
//Connection as above
function available_dates() {
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$encodeArray = array();
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row;
}
} else {
echo "0 results";
}
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
}
available_dates();
$conn->close();
?>
I've just started with functions so I expect my errors to be quite comical!
...do I need to use echo to call the function?
you are not returning anything,you should assign return value to some thing.You should call your function like this.
function available_dates() {
$sql = "SELECT * from DB_Available_Dates";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$encodeArray = array();
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row;
}
} else {
echo "0 results";
}
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
}
$result=available_dates();
You are doing nothing with the return value of your function.
You can echo it or put it in a variable.
echo available_dates();
or
print_r(available_dates());
or
$results = available_dates();
You're returning an array in your code:
$dates = array();
$dates = json_encode($encodeArray);
return $dates;
You should simply echo the json_encode like this:
echo json_encode($encodeArray);
And then take care of the formatting/displaying (alternatively, you could do it like in your first example and echo back the output ready for displaying):
while($row = $result->fetch_assoc()) {
$encodeArray[] = $row["year"]. " - " . $row["Month"]. " " . row["the_days"].<br>";
}
and then
echo json_encode($encodeArray);

Get datas from table and display with OOP

How I can get the comments with OOP from my database? Im trying with below code but it displaying the error. Im new using the classes and I git stuck here trying to reselve this issue.
Below is the code in class Comments:
function getComments(){
$komentet = array();
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$result = mysql_query("SELECT * FROM posts order by mycoment DESC") or die(mysql_error());
while($row = mysql_fetch_array($result)){
array_push($komentet,$row['mycoment']);
}
return $komentet;
}
With the below code, Im trying to display the datas in my web page but I can not.
<?php
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
?>
It returning the following error:
Notice: Undefined variable: comm in C:\xampp\htdocs\profile\uprofile.php on line 194
Fatal error: Call to a member function getComments() on null in C:\xampp\htdocs\profile\uprofile.php on line 194
Full classs is the code below:
<?php
class Comments {
public $datetime;
public $comment;
function insertDate(){
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$this->datetime = date("F j, Y, g:i a");
$sql = "INSERT INTO posts(userid, mycoment, time) VALUES('$id','$this->comment','$this->datetime')";
if(mysql_query($sql)){
echo "Comment Added";
}else{
echo "Comment Failed";
}
}
function getComments(){
$komentet = array();
$connect = mysql_connect("localhost","root","") or die(mysql_error());
$select = mysql_select_db("profile") or die(mysql_error());
$id = $_SESSION['id'];
$result = mysql_query("SELECT * FROM posts order by mycoment DESC") or die(mysql_error());
while($row = mysql_fetch_array($result)){
array_push($komentet,$row['mycoment']);
}
return $komentet;
}
}
the problem you have is you crate the instance of the class Comments inside of a condition, which does not pass:
require_once('comments.php');
if(isset($_POST['postsomething'])){
$comm = new Comments();
$comm->comment = trim($_POST['mycoment']);
$comm->insertDate();
}
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
so you should alter it like this:
require_once('comments.php');
$comm = new Comments();
if(isset($_POST['postsomething'])){
$comm->comment = trim($_POST['mycoment']);
$comm->insertDate();
}
$komentet = $comm->getComments();
foreach($komentet as $cm){
echo "<tr><td>".$cm."</td></tr>";
}
I've made a little work for you and refactored the Comments class using mysqli extension and ridding som DRY (Don't Repeat Yourself) breaches. I highly suggest you to stick on mysqli and avoid any code duplication.
class Comments
{
public $datetime;
public $comment;
function insertDate(){
$id = $_SESSION['id'];
$this->datetime = date("F j, Y, g:i a");
$sql = "INSERT INTO posts(userid, mycoment, time) VALUES('$id', '$this->comment', '$this->datetime')";
if($this->getConnection()->query($sql)){
echo "Comment Added";
} else{
echo "Comment Failed";
}
}
function getComments(){
$komentet = array();
$result = $this->getConnection()->query("SELECT * FROM posts order by mycoment DESC");
while($row = $result->fetch_assoc()){
array_push($komentet, $row['mycoment']);
}
return $komentet;
}
private function getConnection(){
if($this->connection === null)
$this->connection = mysqli_connect("localhost", "root", "", "profile") or die(mysqli_error($this->connection));
return $this->connection;
}
/** #var mysqli */
private $connection;
}

trying to do SELECT in php but i get

So I got a nifty little bit of code set to run along and find me information when I give it a certain KittenID but its not working at all, I am sad. And oh so tired, Can anyone tell me where I have gone wrong? and yes I do have:
<?php
date_default_timezone_set('America/New_York');
//If statements:
//find:
date_default_timezone_set('America/New_York');
if(isset($_POST['Find']))
{
$connection = mysql_connect("ocelot.aul.fiu.edu","userName","password");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{
//select a database
$dbName="spr15_xgotz001";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Personality = $row['Personality'];
$Activity = $row['Activity'];
echo $row['Comments'];
}
}
}
mysql_close($connection);
}
?>
Use
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = " .$_POST['KittenID']);
instead of
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)
Note: Please use mysqli_ for your future projects
You need to privide more context. How are you setting the $_GET['id'].. is it in fact being stored as $_GET['KittenID'] (e.g. https://yoursite.com?view&KittenID=1). If so...
You can set a variable and declare the 'KittenID'
$kittenid = $_POST['KittenID'];
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = $kittenid");
I suggest providing more context. What error are you getting? What do your parameters look like?
Use
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID = " .$_SERVER['KittenID']);
instead of
$result = mysql_query($connection,"SELECT * FROM Kittenz WHERE KittenID =<?php$_POST[KittenID]?>;)

Return a value from a recursive function

I have a function that I can get all the correct values for with an echo, but when I cannot figure out how to get the whole array returned. Could someone help me figure out to get the all of the child users?
$useridarray[] = $userid;
getchildren($useridarray, $useridarray);
function getchildren($array, $totalarray)
{
foreach($array as $arr)
{
$db_name = "dbname";
$connection = #mysql_connect("localhost", "username", "password") or die(mysql_error());
$db = #mysql_select_db($db_name, $connection) or die(mysql_error());
$sql = "
select *
from users
where creator = '$arr'
";
$result = #mysql_query($sql, $connection) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$newchildren[] = $row['id'];
$totalarray[] = $row['id'];
//echo $row['id'] . ' ';
}
mysql_close();
getchildren($newchildren, $totalarray);
}
}
You need to pass by referenceĀ­Docs:
function getchildren($array, &$totalarray)
^
Usage:
$useridarray[] = $userid;
getchildren($useridarray, $useridarray);
var_dump($useridarray); # your result
You need add return before
mysql_close();
return getchildren($newchildren, $totalarray);
I am not familiar with PHP syntax but you likely want to implement a "Stopping Criteria" to return you results. So in your instance it would seem like you would want something where getChildren returns the localResults + recursive getChildren results that are totaled incrementally as you go through your foreach loop.

Problems deleting File PHP

This is my code to pull information from my sql database and then I want to delete the .txt files in each directory, but I can't seem to figure out why it won't delete the files.
<?php
session_start();
$user = $_SESSION['SESS_USERNAME'];
$id = array();
$id = $_POST['selected'];
//Include database connection details
require_once('config_order.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if (!$db) {
die("Unable to select database");
}
//Create query
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
// display query results
while ($row = mysql_fetch_array($query)) {
$c_name = $row['clientname'];
$sitestreet = $row['sitestreet'];
$inspector = $row['inspector'];
}
mysql_close($link);
$client_name = str_replace(" ", "_", $c_name);
$site_street = str_replace(" ", "_", $sitestreet);
$client_name = "{$client_name}.txt";
$site_street = "{$site_street}.txt";
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (unlink($client_path . "/" . $client_name)) {
echo 'File Deleted';
} else {
echo 'File could not be deleted';
}
?>
I think this is because your while loop is overwriting the $c_name, $sitestreet and $inspector variables. This means you will only ever delete the last file.
Is this what you were trying to do? (Edited Again...)
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` IN (".mysql_real_escape_string(implode(',',$id)).")");
while ($row = mysql_fetch_array($query)) {
$inspector = $row['inspector'];
$client_name = str_replace(" ", "_", $row['clientname']).'.txt';
$site_street = str_replace(" ", "_", $row['sitestreet']).'.txt';
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (!file_exists($client_path.'/'.$client_name)) {
echo "File $client_path/$client_name does not exist!\n";
} else echo (unlink($client_path.'/'.$client_name)) ? "File $client_path/$client_name was deleted\n" : "File $client_path/$client_name could not be deleted\n";
}
mysql_close($link);
Try some extra debugging:
$realpath = $client_path . '/' . $client_name;
if (file_exists($realpath)) {
if (is_writable($realpath)) {
if (unlink($realpath)) {
echo "$realpath deleted";
} else {
echo "Unable to delete $realpath";
}
} else {
echo "$realpath is not writable";
}
} else {
echo "$realpath does not exist";
}
On first glance, this is a problem, if $_POST['selected'] is not an array:
$id = array();
$id = $_POST['selected'];
...
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
You are instantiating $id as an empty array, then overwriting it with $_POST['selected'], so $id[0] is the first character of the string $id.
For example, if $_POST['selected'] is 12345:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'"
is equivalent to:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '1'"
Either don't try to access it with an index or do $id[] = $_POST['selected']; to add the element onto the $id array instead.
Whether that is an array or not, you do need to either sanitize that input before you insert it into the query or use prepared statements, though!

Categories