I am using a PHP script to pull comments from my database to populate an app. How the database is set up is any secondary comments, ie replies to comments, will have a reply_id. The issue im seeing is all comments, regarless of replies, are seeing the same replies as the one comment that has it. I tried deleting the array with the secondary comments in it, but to no avail. Could someone point out where I failed to seperate the values?
// Create connection
$conn = mysqli_connect($servername, $username, $password,$db);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
$memory_id=$_POST['memory_id'];
$query ="Select * FROM comment WHERE memory_id= '$memory_id' and reply_id=''";
$dbquery = mysqli_query($conn,$query);
$query2= "Select * FROM comment WHERE memory_id='$memory_id' and reply_id='$comment_id'";
if($dbquery){
$result = array();
while($row = mysqli_fetch_array($dbquery))
{
$temp_array= array();
unset($temp_array['replys']);
$temp_array['user_id']=$row['user_id'];
$temp_array['comment_id']=$row['comment_id'];
$temp_array['text']=$row['comment'];
$comment_id= $row['comment_id'];
$temp_array['replys']=array();
$dbquery2 = mysqli_query($conn,$query2);
if($dbquery2){
while ($row2 = mysqli_fetch_array($dbquery2)){
$temp_array['replys'][]=array(
'user_id'=>$row2['user_id'],
'comment_id'=>$row2['comment_id'],
'text'=>$row2['comment']);
}//Feeds comments
array_push($result, $temp_array);
}
}//pulls initial command
echo json_encode($result);
}
else
{
$response["error"] = TRUE;
$response["error_msg"] = "No memory FOund";
echo json_encode($response);
}
?>
The second query is being executed with $memory_id having the value of $_POST['memory_id']. An easy solution is to move the $query2 line below $memory_id = $row['memory_id'], that way the second query will be executed with the correct memory_id value.
EDIT
A better solution is to prepare your queries instead. Check the mysqli_prepare function.
Related
I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!
I have tried a ton of different versions of this code, from tons of different websites. I am entirely confused why this isn't working. Even copy and pasted code wont work. I am fairly new to PHP and MySQL, but have done a decent amount of HTML, CSS, and JS so I am not super new to code in general, but I am still a beginner
Here is what I have. I am trying to fetch data from a database to compare it to user entered data from the last page (essentially a login thing). I haven't even gotten to the comparison part yet because I can't fetch information, all I am getting is a 500 error code in chrome's debug window. I am completely clueless on this because everything I have read says this should be completely fine.
I'm completely worn out from this, it's been frustrating me to no end. Hopefully someone here can help. For the record, it connects just fine, its the minute I try to use the $sql variable that everything falls apart. I'm doing this on Godaddy hosting, if that means anything.
<?php
$servername = "localhost";
$username = "joemama198";
$pass = "Password";
$dbname = "EmployeeTimesheet";
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
$sql = 'SELECT Name FROM Employee List';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["Name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
There be trouble here:
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
There are three problems here:
mysqli_conect() instead of mysqli_connect() (note the double n in connect)
mysqli_connect_errno should be a function: mysqli_connect_errno()
mysqi_connect_error() instead of mysqli_connect_error() (note the l in mysqli)
The reason you're getting a 500 error is that you do not have debugging enabled. Please add the following to the very top of your script:
ini_set('display_errors', 'on');
error_reporting(E_ALL);
That should prevent a not-so-useful 500 error from appearing, and should instead show the actual reason for any other errors.
There might be a problem here:
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
If the query fails, $result will be false and you will get an error on the mysqli_num_rows() call. You should add a check between there:
$result = mysqli_query($conn, $sql);
if (!$result) {
die('Query failed because: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
The name of your database table in your select statement has a space in it. If that is intended try:
$sql = 'SELECT Name FROM `Employee List`';
i think you left blank space in your query.
$sql = 'SELECT Name FROM Employee List';
change to
$sql = "SELECT `Name` FROM `EmployeeList`";
I have a successful connection to the database through this php script but it is not returning any values even though it is connected. I am checking for the results on my web browser and it just returns a blank screen. I have used the same script (different queries) to access two other tables in the database and they are both working fine. Here is my code:
<?php
$username = "xx";
$password = "xxx";
$host = "xxxxx";
$database="xxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
It is probably some silly mistake that I have over looked but I have been stuck on it for longer than I should! thanks in advance for any feedback
Tried you code locally on some data and it returns everything ok.
I needed to change the select to match my data
So I am 95% sure the problem is in your query / db settings.
I would first check if your columns in database is really called AUTHOR and 'In_order' with the exact capital letters.
MySql names can be case sensitive depending on your db server settings, and this could be the problem
Sidenote: if you can research mysqli and pdo for connecting to DB instead of mysql that is deprecated.
Try this:
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
$num = mysql_num_rows($query);
var_dump($query);
var_dump($num);
echo mysql_error();
and tell us what it all says.
Edit: okay, so it's 231 rows in your table, as the var_dump($num) says. Now let's try and get them at last, but in a slightly more efficient way:
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
I have a feeling that your "for" loop and mysql_fetch_assoc() inside is what plays tricks with you, because both of them use different internal counters.
I have this PHP:
<?php
$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");
if ($connection->connect_error) {
die("Connection failed: " . $Connection->connect_error);
}
$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
$check_emails_sent_result = $connection->query($check_emails_sent_query);
echo $check_emails_sent_result;
?>
This is a small piece of a much larger function on my site. This snippet is simply intended to get the value of the "emails" column (Which is an int column if that makes a difference) of my table where the IP matches the client's IP.
I added a fake entry for 11.111.111.111 in my database, and used the exact same query on PHPmyAdmin's SQL console. I got a result on the PHPmyAdmin console, but nothing is echoed here.
I have also checked that the connection is good, as you can see in my code. Additionally, I pasted another query from another part of my function, which retrieved its data just fine.
AS stupid or obvious as it may be, I can't seem to figure out why this particular query out of almost twenty won't retrieve its data?
Mysqli query() returns and object. Using the object:
<?php
$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");
if ($connection->connect_error)
{
die("Connection failed: " . $Connection->connect_error);
}
$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
if ($check_emails_sent_result = $connection->query($check_emails_sent_query))
{
while($obj = $check_emails_sent_result->fetch_object())
{
$echo $obj->emails;
}
}
?>
You could use fetch_row() instead of fetch_object().
Documentation for the object is here:
http://php.net/manual/en/class.mysqli-result.php
mysqli_query()
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
You can get your email by using
if ($result = $connection->query($check_emails_sent_query)) {
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0]);
}
}
I found a script that uses php long polling.
It uses the following code to see if the text file is changed and returns the content.
This is received by the browser.
How can i change this to read a table and see if there are new events ?
$filename= dirname(__FILE__)."/data.txt";
$lastmodif = isset( $_GET['timestamp'])? $_GET['timestamp']: 0 ;
$currentmodif=filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif =filemtime($filename);
}
$response = array();
$response['msg'] =Date("h:i:s")." ".file_get_contents($filename);
$response['timestamp']= $currentmodif;
echo json_encode($response);
I have a table where there are 'posts'. post_id,content,user_id,posted_time
How can i know if theres a new post ?
You basically just have to fetch a new result, thats it, if you want to check if there are new results since the last execution of the script you have to save the output somewhere (is that what you want to do?)
See the following code, for a regular MySQL query:
<?php
// Connect to your MySQL DB
#$db = mysqli_connect("localhost", "root", "", "database");
// Check connection and echo if an error occurs
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
// Execute SQL Query, replace this with your Query (maybe the one I put in fits for your needs)
$query = mysqli_query($db, "SELECT * FROM posts");
// Transform the result into an array if your you got new elements in the MySQL DB.
$resultat = mysqli_fetch_assoc($befehl);
// Close connection
mysqli_close($db);
?>