I lack some experience with PHP/MySQL environment. I have a MySQL table called MyTable. In it I have a field called RowTime of type DATETIME NOT NULL. After selecting the row in PHP, I want to check whether RowTime is older or younger than 3 days.
Given all the different types of time types, can someone please help completing the following code (I'm deliberately omitting various error handling):
$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$dbquery = "SELECT RowTime FROM MyTable WHERE Id='" . $myId . "'";
$result = mysqli_query($dblink, $dbquery);
$numrows = mysqli_num_rows($result);
// ... Verify $numrows == 1 ...
$myRow = mysqli_fetch_assoc($result);
$rowTime = $myRow['RowTime'];
// NEED HELP HERE to check whether $rowTime is older or younger than 3 days
mysqli_free_result($result);
You can use special SQL operator to check that your date older than 3 days:
$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$dbquery = "SELECT RowTime, IF(RowTime + INTERVAL 3 DAYS > now(), true, false) as isYounger FROM MyTable WHERE Id='" . $myId . "'";
$result = mysqli_query($dblink, $dbquery);
$numrows = mysqli_num_rows($result);
// ... Verify $numrows == 1 ...
$myRow = mysqli_fetch_assoc($result);
$rowTime = $myRow['RowTime'];
if($myRow['isYounger']) {
//record is younger
} else {
//record is older
}
mysqli_free_result($result);
You can use the following query:
SELECT RowTime,TIMEDIFF(NOW(),RowTime)>"72:00:00" AS "Old" FROM MyTable ;
This will introduce column "Old" which will be 1 if RowTime is older than 3 days. Otherwise it'll be 0. Please note that this doesn't take the timezone into account.
Related
$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?
I have this code:
<?php
//MYSQL
$dbserver="..."; //adresa MySQL
$dblogin="..."; //jméno uživatele MySQL
$dbheslo="..."; //heslo MySQL
$dbnazev="..."; //název databáze MySQL
$mysqli = new mysqli($dbserver, $dblogin, $dbheslo, $dbnazev);
if ($mysqli->connect_error) {
die('Nepodařilo se připojit k MySQL serveru (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'"); // nastavíme kódování MySQL
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){
$tempid = $row['tempid'];
$jmeno = $row['jmeno'];
$prijmeni = $row['prijmeni'];
$email = $row['email'];
$bydliste = $row['bydliste'];
$souhlas = "on";
$aktuality = "on";
$timestamp = time();
$hash = md5("77c0a83besxxxcg1a190ab90d".time().$tempid.rand(10000000, 99999999));
$poznamky = "import19052018";
$vloz ="INSERT into `potvrzenotest` set jmeno='".$jmeno."', prijmeni='".$prijmeni."', bydliste='".$bydliste."', email='".$email."', souhlas='".$souhlas."', aktuality='".$aktuality."', timestamp='".$timestamp."', hash='".$hash."', poznamky='".$poznamky."';";
$result=$mysqli->query($vloz);
$cas = date('H:i');
echo '['.$cas.'] ID '.$tempid.' imported.', PHP_EOL;
}
mysqli_close($mysqli); .
?>
I have one table with some data and I have to copy it to another table with some additional data (like hash etc.).
When I run the code above, I got this:
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
So, only 1 row is being copied.
Could you please help me, where is the problem?
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){ ... }
This loop will never end. And it will fetch the first row again and again.
You should execute the query outside the loop:
$selectResult = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL");
while ($row = $selectResult->fetch_assoc()) { ... }
As a side note: Consider to use a prepared statement for your INSERT statement in the loop. This will prevent SQL syntax errors if some of the values may contail special characters like '. If you run them in one transaction, you might even improve the performance.
I am trying to make simple page which will return values from MySQL table, but the problem is that if I want to use condotions in query then it doesn't work.
My PHP page:
<?php
$servername = "10.10.10.10";
$username = "username";
$password = "password";
$dbname = "GENERIC_TABLES";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT WO_NUM+1 from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> WO Number ". $row["WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So, WO_NUM column has numbers like 1, 2, 3 etc.
I want to get the last one + 1
So if I do like:
$sql = "SELECT WO_NUM from GENERIC_TABLES.WO_NUMBERS ORDER BY WO_NUM DESC limit 1";
Then it works fine, but if I want to make it WO_NUM + 1 then it returns nothing.
Why it happens like that and is there any way to get what I want using MySQL?
I don't want to get WO_NUM and then using PHP make it + 1, since I also need INSERT to the table values and I would like to understand why it doesn't work.
As you realized, WO_NUM+1 changes the column name in the resulting array, so use an alias WO_NUM+1 as NEW_NUM. However I would not bother with the sorting and limit. Consider MAX():
SELECT max(WO_NUM)+1 as NEW_NUM from GENERIC_TABLES.WO_NUMBERS
As it has been pointed by AbraCadaver, I missed that if I am using WO_NUM + 1 then column name changing so that is why i didn't get any output, so using alias solved problem.
I am calculating AGE by DATE from DOB field, then I want to push it into AGE with correct age based on DOB . So As I debug The DOB calculating to AGE is works, but it cannot update AGE the code:
<?php
$servername = "localhost";
$username = "usernameexmaple";
$password = "passworking";
$dbname = "dbnameworking";
// Create connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id as ID, YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age
FROM regio_users";
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$newage = $row['age'];
$newid = $row['ID'];
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result2 = $conn->query($sql);
if ($result2){
echo "done"."<br>";
}
}
}
else {
echo "0 results";
}
$conn->close();
?>
It echos DONE for every ID but not updating anything at all.
You have used $result2 = $conn->query($sql); which is incorrect. You have to use $result2 = $conn->query($sql2); as $sql2 is the new query you formed.
This can be done with a single line SQL, rather than using PHP to loop through all the rows to only update the age:
UPDATE `regio_users` SET `age` = YEAR(CURRENT_TIMESTAMP) - YEAR(`dob`) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(`dob`, 5));
As saty pointed, use correct variable name.
Check if autocommit is on. If not, make sure you commit the data. Check for its syntax in PHP.
I want to have a "toplist" type thing for my forum. I have a kill log for a pc game. So in my sql table 'victims' i have couple of rows for data. I want to take to use $killforumid to sum $score for the entire table. there are multiple entries with the same $killforumid, and i want to sort with that and add up the score for that user.
It would look like this:
User 1 = 1000 points, 60 kills
User 2 = 5000 points, 100 kills
PHP code:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT score, killforumid FROM hcvictims";
$result = $conn->query($sql);
if you're using RightClick query (as i'll advise):
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT sum(score), killforumid FROM hcvictims GROUP BY killforumid ORDER BY sum(score) DESC";
$result = $conn->query($sql);
while($row = $result->fetch_row())
{
echo "killforumid: " . $row[1] . ", score : " . $row[0] . "\n";
}
/* free result set */
$result->free();
see: mysqli-result object,
fetch-row method