So I have a website and I am trying to display the last update time of the mySQL server, I've looked around but still having problems. Here is my code
$sql = 'SHOW TABLE STATUS FROM alumni LIKE "alumni_data"';
$tableStatus = mysqli_query($link, $sql);
if (!$tableStatus) {
$error = 'Error getting update status: ' . mysqli_error($link);
include 'error.html.php';
exit();
}
while ($array = mysqli_fetch_array($tableStatus)) {
$updatetime = $array['Update_time'];
}
echo '<center>Last Updated: ' . $updatetime . '</center>';
What happens is nothing prints out, its like it never found the update time. I have manually typed that query so I am pretty sure it works.
Thanks
Related
currently I'm working on a project that fills up a main-database.
Right now it consists of two scripts and a source-database.
What I'm trying to do is:
Script 1 connects to source-db, grabs a city and passes the city as a session-variable via header('Location Script2.php') to Script 2.
Script 2 does a lot of work then (collecting specific data, stores in Array) and saves it in the main-database.
That works fine so far.
Script 2 shall now start Script 1 again, to fetch the next city in the db.
That's where I'm stuck (I tried all solutions I could find on here):
again via Header
CURL
shell_exec
etc.
So far, nothing worked.
Any suggestions, ideas or input are very much appreciated!
Many thanks in advance and I look forward to learn from any knowledgeable person on here!
Great evening to you all
Here's the code:
Script 1:
Grab the first city with Status "1" (when finished "Status" is updated to "0"):
$con = new mysqli($host, $user, $password, $dbname)
or die ('Could not connect to the database server' . mysqli_connect_error());
// Wählt immer die erste Zeile mit Status "0" aus
$query = "SELECT City FROM citydb WHERE Status = '1' LIMIT 1";
//Packt Stadtname in $location
if ($stmt = $con->prepare($query)) {
$stmt->execute();
$stmt->bind_result($field1);
while ($stmt->fetch()) {
$loc = $field1;
}
$stmt->close();
}
// Überträgt die Variable $location
if ( empty($loc) !== FALSE){
echo "Nichts mehr da!";
exit;
} else {
$_SESSION['$location'] = $loc;
header('Location: xxxxxxx/xxxx-get-basicdata.php');
exit;
}
Script 2:
Processing, saving, restart
$dbkeys = "(" . implode(", ", array_keys($details)) . ")";
$dbvalues = "('" . implode("', '", $details) . "')";
$query = "INSERT INTO data " . $dbkeys . " VALUES " . $dbvalues;
// // UPDATING STATUS IN CITIES-DB
$query = "UPDATE citydb SET STATUS = 0 WHERE City = ('$city')";
if(mysqli_query($conn, $query)){
/////////// THIS IS WHERE I'M STUCK
/////////// here script 1 should be called (at least I thought so)
} else{
echo "ERROR: Not able to execute $sql. " . mysqli_error($conn);
exit;
}
PS: Just for the case the same question came up before or else: I'd be happy if someone could just give me a hint/link. I don't want to have a perfect solution, just an idea what to look into.
Once again I come back to all of you with another question.
I have tried everything in my mind as well as most of the recommendations I have found on the web and here in Stackoverflow but nothing seems to fix this issue for me.
For some reason the sql command in my code is returning false even though it should not.
Here is my php file called (dbRKS-DBTest.php)
<?php
//Gets server connection credentials stored in serConCred.php
//require_once('/../prctrc/servConCred2.php');
require_once('C:\wamp64.2\www\servConCred2.php');
//SQL code for connection w/ error control
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(!$con){
die('Could not connect: ' . mysqli_connect_error());
}
//Selection of the databse w/ error control
$db_selected = mysqli_select_db($con, DB_NAME);
if(!$db_selected){
die('Can not use ' . DB_NAME . ': ' . mysqli_error($con));
}
//VARIABLES & CONSTANTS
//Principal Investigator Information
$PI_Selected = '6';
//Regulatory Knowledge and Support Core Requests variables
$RKS_REQ_1_Develop = '1';
//This sets a starting point in the rollback process in case of errors along the code
$success = true; //Flag to determine success of transaction
//start transaction
$command = "SET AUTOCOMMIT = 0";
$result = mysqli_query($con, $command);
$command = "BEGIN";
$result = mysqli_query($con, $command);
//Delete this portion of code afyer testing is finished
//Core Requests saved to database
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop')";
//*************TEsts code for "SCOPE_IDENTITY()" -> insert_id() for mysql
$sqlInsertId = mysqli_insert_id($con); //This value is supposed to be 0 since no queries have been executed.
echo "<br>MYSQLi_INSERT_ID() value before query should be 0 and it is:= " . $sqlInsertId;
//Checks for errors in the db connection.
$result = mysqli_query($con, $sql); //Executes query.
if($result == false){ //Checks to see for errors in previews query ($sql)
//die ('<br>Error in query to Main Form: Research Proposal Grant Preparation: ' . mysqli_error($con));
echo "<br>Result for the sql run returned FALSE. Check for error in sql code execution.";
echo "<br>Error given by php is: " . mysqli_error($con);
$success = false; //Chances success to false is it encounted an error in order to rollback transaction to database
}
else{
//*************TEsts code for "SCOPE_IDENTITY()" -> insert_id() for mysql
$sqlInsertId = mysqli_insert_id($con); //Saves the last id entered. This would be for the main table
echo "<br>MYSQLi_INSERT_ID() value after Main form query= " . $sqlInsertId; //Displays id last stored. This is the main forms id
$MAIN_ID = mysqli_insert_id($con); //Sets last entered id in the MAIN Form db to variable
}
//Checks for errors or craches inside the code
// If found, execute rollback
if($success){
$command = "COMMIT";
$result = mysqli_query($con, $command);
echo "<br>Tables have been saved witn 0 errors.";
}
else{
$command = "ROLLBACK";
$result = mysqli_query($con, $command);
echo "<br>Error! Databases could not be saved. <br>
We apologize for any inconvenience this may cause. <br>
Please contact a system administrator at PRCTRC.";
}
$command = "SET AUTOCOMMIT = 1"; //return to autocommit
$result = mysqli_query($con, $command);
//Displays message
//echo '<br>Connection Successfully. ';
//echo '<br>Database have been saved';
//Close the sql connection to dababase
mysqli_close($con);
?>
Here is my php frontend html code named (RPGPHomeQueryTest.php)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<form id="testQuery" name="testQuery" method="post" action="../dbRKS-DBTest.php" enctype = "multipart/form-data">
<input type="submit" value="Submit query"/>
</form>
</html>
And here is how my database looks (rpgp_form_table_3):
So, when I open my html code, All I will see is a button since its all the code there is there. Once you press the button, the form should submit and execute the php code called (dbRKS-DBTest.php). This should take the predetermine values I already declared and saved them to the database called (rpgp_form_table_3). This database is set to InnoDB format.
Now, the output I should be getting is a message saying "Tables have been saved witn 0 errors." but the problem is that the message I am getting is this one bolow:
I honestly don't know why. I am posting this message to find guidance to this issue. I am still learning by myself and its been very did-heartedly to not find a solution this fixing this.
As always, I thank you for your patient and guidance! Let me know what other details I can provide.
Here is the SQL code you run:
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop')";
You are inserting data into rpgp_form_table_3. From the screenshot, we can see that table has several (7) fields yet you are only inserting 2 fields. The question then is: do you need to specify a value for all fields?
The error you are getting states
Error given by php is: Field 'idCollaRecord_1' doesn't have a default value Error! Databases could not be saved.
It's clear that you have to insert the row by specifying a value for each column, not just the two columns you are interested in.
Try
$sql = "INSERT INTO rpgp_form_table_3 (idPl, RKS_REQ_1_Develop, idCollaRecord_1, idCollaRecord_2, idCollaRecord_3, idCollaRecord_4)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop',0,0,0,0)";
Try this insert code. If the PI_Selected is NUMERIC use the First one. If it is string use the second one
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop) VALUES (" .
$PI_Selected . ",'" . $RKS_REQ_1_Develop . "')";
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop) VALUES ('" .
$PI_Selected . "','" . $RKS_REQ_1_Develop . "')";
The following query string is working from the phpMyAdmin SQL panel, but not from my php script.
I checked with mysqli_affected_rows()... it returns 0. But from SQL panel it affects particular 1 row.
The user account for the MySQL db I am using from php script has UPDATE privilege set.
UPDATE forecast SET forecastAmount = 1000.00, updBy='Admin User', updDt=now() WHERE companyId=2 AND forecastDate='2018-03-01';
PHP Script:
$forecastDate = date('Y-m-d', mktime(0, 0, 0, $_POST['forecastMonth'], ($i+1), $_POST['forecastYear']))."<br>";
$queryStringForecastUpdate = "UPDATE $tbl_forecast
SET forecastAmount = ".$_POST['day'][$i].
", updBy='".$_SESSION['ssnName'].
"', updDt=now()".
" WHERE companyId=".$_POST['forecastCompany'].
" AND forecastDate='$forecastDate';";
if (mysqli_query($dbConn, $queryStringForecastUpdate)) {
echo mysqli_affected_rows($dbConn);
$_SESSION['sccMsg'] = "Updated successfully";
} else {
$_SESSION['errMsg'] = "Error: " . $queryStringForecastUpdate . "<br>" . mysqli_error($dbConn);
}
Can anyone pls tell me what might goes wrong here?
got the problem: I mistakenly added a <br> at the end of $forecastDate assignment in line 1.
I have been reading about the Commands out of sync; you can't run this command now problem for some time now, and see that you cannot have any unread results left, which makes sense to me. However, in the following case, I don't see which results I am missing to free. I have left out the irrelevant things from my PHP and SQL code below.
# Set local variables
$sql = "
SET #STARTDATE = '2014-09-01';
SET #RANK = 0;
";
if (mysqli_multi_query($conn, $sql)) {
# Success: do nothing else
} else {
# Failure: output the error message
echo "Error: " . $sql . "<br>" . $conn->error;
}
# Fetch and store the results
$sql = "
SELECT * FROM MyTable
";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
The second query (the if (!$result) block) returns the infamous Commands out of sync error. If I comment out the first part, the second query runs no problem. If I change the first query into only one SET statement instead of two, the second query runs no problem. Therefore, it seems that I have to clear the 'success-flag' of every individual SQL statement from the first part. Is this correct? If so, how shall this be done?
EDIT: indeed it seems you have to flush all results in between. Adding the following line between part 1 and part 2 solves the problem.
while (mysqli_next_result($conn)) {;} // Flush multi_queries
I found this solution in a user comment on the PHP manual: http://nl3.php.net/manual/en/mysqli.multi-query.php
Quite simply, your first query
SET #STARTDATE = '2014-09-01';
SET #RANK = 0;
Will generate 2 result sets and until they have been processed, even though the result will be just a status you cannot continue.
So you need to do something like this :-
if (mysqli_multi_query($conn, $sql)) {
do {
/* unload result set */
if ($result = $mysqli->store_result()) {
// Check status
$result->free();
}
} while ($mysqli->next_result());
} else {
# Failure: output the error message
echo "Error: " . $sql . "<br>" . $conn->error;
}
Of course you should probably check for errors in that loop
We have a website that accesses a SQL Server 2005 server for one query. Currently, the site is in ASP, we are moving it to PHP, and the PHP one is currently being tested. After we run a few successful queries on the PHP site, it returns the "Error in database query. Please try again later" line in the code below. When I rewrote that line with sqlsrv_errors to elaborate, it told me that the table didn't exist. There are about 40 tables in the database, but after the error happens it only shows 8 of them in Management Studio. However, if I allow it to sit for about 5 minutes, all of the tables are restored. No matter how many times the old ASP site is used, the table does not do this. However, when the tables disappear from using the new site, the old site shows inaccessible for a few minutes until the tables re-appear in SQL Server management studio. I didn't see any kind of connection limits on the SQL Server, so I don't know whether it's something I'm doing in the PHP SQL queries or within the SQL Server properties.
<?php
include ("dbvals.inc.php");
if (!empty($_POST['lastnamebox'])) {
$dbhandle = sqlsrv_connect($dbServer, $connectioninfo);
if($dbhandle == false){
echo "Error connecting to database. Please try again later. ";
}
else{
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
$params = array();
array_push ($params, $_POST['lastnamebox']);
$results = sqlsrv_query($dbhandle, $query, $params);
if($results == false){
echo "Error in database query. Please try again later.";
//This is printed when database tables temporarily disappear
}
else
{
$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
if($row){
do{
echo "<tr><td class='tablecell'>";
echo $row['LastName'] . "," . $row['FirstName'] . "<br>";
echo "Address: " . $row['Address'] . "<br>";
echo "City, State, Zip: " . $row['CSZ'] . "<br>";
echo "</tr></td'>";
}while($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC));
}
else{
echo "No results found. Please try another query.";
}
}
}
sqlsrv_free_stmt($results);
sqlsrv_close($dbhandle);
}
else {
echo "Please type a value in the search box.";
}
?>
The $query is wrong to begin with. Change it to:
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
Not sure about the tables disappearing though. What driver are you using?
Just another issue I'm seeing with the code not sure if it's related to your problem. or another copy error but here it is.
if ($r1 = sqlsrv_fetch_array($results)) {
while( $row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC)){
The first fetch should also have '($results,, SQLSRV_FETCH_ASSOC)'
Additional that check is going to eat the first returned record which may or may NOT be what you intended.
Also it is possibly that PHP seeing some results in the while as false even though they aren't and the server is still waiting on you to finish getting the rest. Seen code like that cause 'Server has got away' errors in MySQL which could be what is going on here as well.
Not sure of the syntax but a sqlsrv_clode_cursor() just before the connection close might also fix your issue if there's some kind of connection polling going on. Could be simply running out of connection or getting old one in a incorrect state.
SELECT * FROM Person WHERE AND LastName LIKE
Looks like there something missing between the WHERE and AND to me.
I don't know SQL Server really so it could allow that but it's not standard SQL. Depending on how it's reacting to that error I could see it 'Going away' so to say and reporting tables missing.