Selecting last row in database not working using PHP - php

I have a php code that will select the last row in mysql using database but this error comes out:
syntax error, unexpected '$result' (T_VARIABLE)
My php code:
$con = mysqli_connect("localhost","root","","productno") or die("Error " . mysqli_error($con));
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT Alibaba FROM records ORDER BY Date DESC LIMIT 1");
if (mysqli_num_rows($result) > 0)
{
$s_Alibaba = mysqli_fetch_row($result);
$sql_Alibaba = $s_Alibaba[0]; //Compare with the last record
}
echo $sql_Alibaba;
Any idea how to fix it? thanks

The problem is, date is a reserved keyword in mysql. Escape it with ` characters around:
$result = mysqli_query($con, "SELECT Alibaba FROM records ORDER BY `Date` DESC LIMIT 1");
See here: http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html

Related

LIMIT doesn't work in MariaDB - Tried a lot of things

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "igscript";
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$query = "SELECT * FROM lastsearches";
$result = mysqli_query($con, $query);
if(mysqli_connect_errno()) {
die("DB Error: " . mysqli_connect_error() . " ( " .mysqli_connect_errno() . ")");
}
while($row = mysqli_fetch_assoc($result)) {
$query = "SELECT * FROM lastsearches Order By data DESC LIMIT 1;";
echo '<center><p>'.$row["name"].'</p> </center><hr>';
if(!mysqli_query($con, $query)) {
die('Error : '.mysqli_error($con));
}
}
$result = mysqli_query($con, $query);
Whenever i use either LIMIT 1, or LIMIT 10; at $query, it has no effect at all. Still displays the same amount of rows. I tried also TOP 10 or TOP(10) as I seen on internet, and i'm getting
Error : You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '10 name FROM lastsearches Order By data DESC LIMIT 1' at line 1
$query = "SELECT TOP 10 name FROM lastsearches Order By data DESC";
-> this was the query;
Also the first query worked properly in phpmyadmin, section SQL.
The query from which you are actually displaying results is this one:
$query = "SELECT * FROM lastsearches";
$result = mysqli_query($con, $query);
If you want to limit the results, you need to edit that query instead i.e.
$query = "SELECT * FROM lastsearches Order By data DESC LIMIT 1";
$result = mysqli_query($con, $query);
I'm not sure what you are trying to achieve with the query in your while loop, but it is not doing anything inside that loop so you can probably remove it.
TOP 10 is SQL Server syntax, not MySQL. MySQL uses LIMIT 10 with a very similar effect.
Since I don't see TOP 10 in your code, could it be some interface package that is tied to SQL Server?

Query would run directly on MySQL but not through PHP

I have a simple MySQL query
select * from tutor where verified = 0 and alert_by < '2015-08-05' LIMIT 0,1
Now, running this directly through phpMyAdmin provides the desired results, however, when this query is being executed through a set of PHP statements, it doesn't return anything. Below is my code in PHP
$this_date = date("Y-m-d");
$query = "select * from tutor where verified = 0 and alert_by < '$this_date' LIMIT 0,1";
$contact = mysqli_query($conn, $query);
$row = $contact->fetch_array(MYSQLI_ASSOC);
However, the $row is empty, I can't seem to figure this out. I know this seems trivial, but its a little annoying.
Note: Removing "and alert_by < '$this_date'" from the query, works fine.
Check
Connection
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Use mysqli_query like this
$contact = mysqli_query($con,"select * from tutor where verified = 0 and alert_by < '$this_date' LIMIT 0,1");
Use fetch array like this (Example #2 Procedural style)
$row = mysqli_fetch_array($contact, MYSQLI_ASSOC)

MySQL Database PHP Specific Rows

My current code is this:
<?php
$con=mysqli_connect("stevie.heliohost.org","rbxdataa_Art","mydata123art");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
mysqli_select_db($con, "rbxdataa_Data");
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
$sql = "SELECT * FROM EventRecord WHERE EventType='$GetType' ORDER BY EventId DESC";
$sql_run = mysqli_query($con, $sql);
while($sql_row = mysqli_fetch_assoc($sql_run)){
echo $sql_row['EventId'].'<br>';
}
mysqli_close($con);
?>
As I am currently very new to PHP and MySQL, I have no idea why this code will not work. I am also confused as to how I would make it echo only the top ($Amount) as determined by how large the "EventId" value is.
My intent is to gather the [$Amount] highest rows in the table with the EventType $GetType.
I am aware of SQL Injection vulnerability, however for my purposes this does not affect me.
Error:
"Parse error: syntax error, unexpected T_STRING on line 4"
As I see, you have a normal code, may be you have no any rows in DataBase with requested EventType ?
At second: you have SQL Injection vulnerability. Use PDO and Prepared Statements instead your mysqli_query code.
If you want to get the row with the max eventid, you need do this:
$sql = "SELECT MAX(EventId) FROM EventRecord WHERE EventType='$GetType';
is not necessary order by eventid when u can get the max using MAX(An AGGREGATION FUNCTION)
P.D: you can add more attributes in select statement.
Try this
if you need highest amount with EventType.
$sql = "SELECT MAX(amount_field) FROM EventRecord WHERE EventType='$GetType';
If you want record sorted based on amount from highest to lowest then order by amount desc. (if you have amount column in table)
<?php
$con=mysqli_connect("Removed for Privacy");
mysqli_select_db($con, "Removed") or die(mysqli_error());
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
$sql = "SELECT * FROM EventRecord WHERE EventType='$GetType' ORDER BY amount DESC";
$sql_run = mysqli_query($con, $sql);
while($sql_row = mysqli_fetch_assoc($sql_run)){
echo $sql_row['EventId'].'<br>';
}
mysqli_close($con);
?>

trying to count entries in a database

I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$con=mysqli_connect($db_host,$db_user,$db_pass,$db_name); // Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,

Using PHP to pull data from MySQL table column randomly

I am using the following (assume I already plan to change these to mysqli at a later date and am aware of the insecurity of the queries used), to pull text strings from rows in one column in a MySQL table and the output in a browser would, ideally, be a randomly selected string from this column:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die(mysql_error ());
$query="SELECT * FROM `tablename` ORDER BY RAND() LIMIT 0,1;";
$result=mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($rs)) {
$rows[] = $row;
}
mysql_close();
$max = count($rows) - 1;
Using the following echo line to achieve the last bit in the browser:
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4]$
?>
I receive the error "PHP Notice: Undefined offset: 0 in script.php on line 19" in reference to this echo line (which, admittedly, was pieced together from other threads and tutorials, so I do not follow completely), however, I've since resolved all other errors logged and observed, so if possible, how can I amend this so the output is just a single row (the text within it) from the column?
Faster and better than using RAND()
$conn = mysqli_connect($host,$username,$password, $database);
if($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$total_rows = 20; //Generate Random number. You could get $total_rows with a first query counting all rows.
$selected_row = mt_rand(0, $total_rows);
//$selected_row -= 1; //just in case you randomized 1 - $total_rows and still need first row.
//Use the result in your limit.
$query="SELECT * FROM `tablename` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["columnname"];
}
Edit it from mysql to mysqli (on the fly). You would not want to use RAND() if your table is very large. Believe me!
In your SELECT-statement, you are telling the database to order the strings randomly. So just get the first one and echo it:
$row = mysql_fetch_array($rs)
echo $row['name_of_field_you_want_to_echo'];
You never define the variable $rs. Other than that...
If you are selecting the first items from a SQL query, you don't need to specify both the limit and top.
$result = mysql_query("SELECT * FROM `tablename` ORDER BY RAND() LIMIT 1");
Since that will ever return one row, you can use mysql_fetch_row
$row = mysql_fetch_row($result);
and then you can get the field from that row with
echo $row["column_name"];

Categories