I am trying to get the results of a SQL query using WHERE, whenever I use the $_GET variable it doesn't work, now I have echoed the $query variable and it shows the value of $_GET['idced'] but for some reason it doesn't do the query thus the loop doesn't show anything.
But when I manually type in the value that I want to compare, it works perfectly fine... any help would be greatly appreciated.. I also know that their might be some security issues with using GET but its a local app so it's not a concern.. heere is the code I have:
<?php
$mysqli = new mysqli("localhost", "cx", "", "cxtrack");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$idced_history = mysqli_real_escape_string($mysqli, $_GET['idced']);
//This is the query that is not working:
$query = "SELECT * FROM applications WHERE idced = $idced_history;";
if ($result = $mysqli->query($query)) {
//This loop works fine when I replace $idced_history with a value of idced
while ($row = $result->fetch_assoc()) {
$curenttime=$row["applicationposition"];
$time_ago =strtotime($curenttime);
echo "<div style='background:red; position:relative; top:2.6em; margin-bottom:1%;'>";
echo "<a href='#'>".$row["applicationposition"]."</a><br/>";
echo "Applied On: ".$row["applicationdate"]." ( ". timeAgo($time_ago) ." ) <br>";
echo "Via: ".$row["applicationtype"]."</div>";
}
$result->free();
}
$mysqli->close();
?>
sometime it not work that way.. try change to:
$query = "SELECT * FROM applications WHERE idced = ".$idced_history;
It didn't work because, idced you get from url is a string and you should spare strings from the sql query with single quotes. Otherwise, mysql act like to your variable as a table name.
try
"SELECT * FROM applications WHERE idced = '$idced_history'";
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'm using PHP to try and select a single row from a table in my MySQL database. I've run the query manually inside phpMyAdmin4 and it returned the expected results. However, when I run the EXACT same query in PHP, it's returning nothing.
$query = "SELECT * FROM characters WHERE username=".$username." and charactername=".$characterName."";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
And when I test this in browser I get the "No results..." echoed back. Am I doing something wrong?
This isn't a duplicate question because I'm not asking when to use certain quotes and backticks. I'm asking for help on why my query isn't working. Quotes just happened to be incorrect, but even when corrected the problem isn't solved. Below is the edited code as well as the rest of it. I have removed my server information for obvious reasons.
<?PHP
$username = $_GET['username'];
$characterName = $_GET['characterName'];
$mysqli = new mysqli("REDACTED","REDACTED","REDACTED");
if(mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `characters` WHERE `username`='".$username."' and `charactername`='".$characterName."'";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
$mysqli->close();
?>
It's failing: $mysqli = new mysqli("REDACTED","REDACTED","REDACTED"); because you didn't choose a database.
Connecting to a database using the MySQLi API requires 4 parameters:
http://php.net/manual/en/function.mysqli-connect.php
If your password isn't required, you still need an (empty) parameter for it.
I.e.: $mysqli = new mysqli("host","user", "", "db");
Plus, as noted.
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Footnotes:
As stated in the original post. Strings require to be quoted in values.
You need to add quotes to the strings in your query:
$query = "SELECT *
FROM characters
WHERE username='".$username."' and charactername='".$characterName."'";
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 have a php file and a database.
<?php
$con=mysqli_connect('localhost','xxxx','xxxxx','joomla30');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM countries where continent_code='EU'") or die (mysqli_error($con));
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$orders[] = array(
'CountryCode' => $row['countrycode'],
'CountryName' => $row['countryname'],
'Select' => $row['Select']
);
}
echo json_encode($orders);
mysqli_close($con);
?>
I got the Database file from - http://www.geekality.net/2011/08/21/country-names-continent-names-and-iso-3166-codes-for-mysql/
The query - $query = "SELECT * FROM countries "; doesn't return anything.
The query - $query = "SELECT * FROM countries where continent_code='AS'"; works perfect.
whereas, $query = "SELECT * FROM countries where continent_code='EU'"; does't return anything.
Similarily 'NA','AF' did not work and others work perfect.
Note: All the above queries works well in phpmyadmin.
I dono the reason for this partial execution of this query.
Expecting a clear answer and correction for the same.
Update:
Problem solved. Its a json problem.
I encoded the connection into UTF-8 and its working now correctly.
You should not use the native functions mysql_ ... should use PDO
Example:
//Connect to DB
$Conexion = new PDO('mysql:dbname=my_db;host=localhost', 'UserDB', 'PasswordDB');
//Prepare query
$Data = $Conexion->prepare("SELECT * FROM countries");
//Execute query
$Data->execute();
//row Count
if($Data->rowCount()>=1) {
$Array = $Data->fetchAll();
//Process print data
foreach ($Array AS $Key => $Value) {
echo $Value['Column'];
}
}
else {
echo 'No Data';
}
I just added mysql_set_charset( 'utf8',$connect);
Its working fine now.
Try removing trailing spaces (look after "countries"). ---> FROM countries ";
I found the same problem in an old PHP version.
I can't get the following code to display items from the database where the parent_id is equal to the id.
Here is the code below.
// Query member data from the database and ready it for display
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT * FROM categories WHERE id=parent_id");
if (!$dbc) {
// There was an error...do something about it here...
print mysqli_error();
}
while ($row = mysqli_fetch_assoc($dbc)) {
echo '<li>' , $row['category_name'] , '';
}
I think I know what I'm doing wrong how can I have this query check a previous query?
I'd put the SQL query in a var so you can output it, then try this direct in the database to see if there are any matching rows:
$mysqli = new mysqli("localhost", "root", "", "sitename");
$query = "SELECT * FROM categories WHERE id=parent_id";
echo $query;
i think this line should be rethought:
if ($row['parent_id'] == $row['id']) {
cause are u sure its the correct logic?
Try do do something like:
if ($row['parent_id'] == $row['id']) {
echo '<li>' , $row['category_name'] , '';
}
else {
echo "there is no match!";
}
And see if the problem is, in fact, not in the SQL query but in you app logic (which I think is more likelly).
That said try to debug SQL queries with phpMyAdmin. Just post the query you want there and check for the output. If the output is ok, look into your logic, if not look into your query.
Do try to split your problem into smaller chunks, makes your debugging much easier.
Hope it helps.