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.
Related
I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And get the following error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page
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 . "')";
I know this has been asked like a million times now.
I tried several solutions I found here but still it doesn't work for me.
What i want to do is SELECT Values out of a simple MySQL Table.
The Values are inserted every five minutes by a program I have written.
I catches all mp3 files in a selected folder and inserts its ID3 Tags into the Table tb_song.
These files should then be SELECTED with the PHP Script and an Android App should Play these files with their URL.
The Database and PHP Code works.
If I just echo all selected values it works fine.
But converting and printing out the encoded array just throws an blank screen.
Could it be that JSON Objects are limited to size?
I've got about 500 entries in tb_song.
Here's my code.
<?php
require_once('config.php');
$connection=new mysqli($server,$user,$password,$database);
$songs=array();
$sql=("SELECT Title,Artist,Album FROM tb_song");
$result=$connection->query($sql);
while($row=$result->fetch_assoc())
{
$temp=array();
$temp['Title']=$row['Title'];
$temp['Artist']=$row['Artist'];
$temp['Album']=$row['Album'];
array_push($songs,$temp);
}
json_encode($songs);
echo(json_encode($songs));//just for testing purposes
$connection->close();
?>
You can distil your code down to this. Plus adding some error checking!
<?php
/* add next 2 lines while testing,
especially if you are using a live hosting site
where error reportinf will be turned off
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
// Check connection is good
if ($connection->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();
$sql = 'SELECT Title,Artist,Album FROM tb_song';
$result = $connection->query($sql);
if ( ! $result ) {
echo $connection->error;
exit;
}
while($row=$result->fetch_assoc()) {
$songs[] = $row;
}
$jstring = json_encode($songs);
if ( json_last_error() > 0 ) {
file_put_contents('json-output.txt', json_last_error_msg());
}
echo $jstring;
//add this line for testing
file_put_contents('json-output.txt', $jstring);
exit;
?>
I finally figured it out.
I guess this is not the standard which's happening to all people but anyway.
Before I'll post my code I want to say a few things for people who are running into the same problem:
Make sure you're only passing strings without 'ä','ü' or whatever letter that is not in the english alphabet.
You need to give your JSON Object a Name, otherwise it could cause problems.
<?php
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
if ($connection->connect_error) {
die('Connect Error (' . $connection->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();//Create Array
$sql = 'SELECT * FROM tb_song';
$result = $connection->query($sql);
while($row=$result->fetch_assoc()){
array_push($songs,$row);//Insert $row in $songs
}
echo json_encode(array('Songs'=>$songs));//Giving JSON Object a proper Name and //encode
$connection->close();
?>
Basically, I have some rows that look like the following image:
Each ExampleUser has an ID and that ID isn't going to change at all.
I need the sql to read what ever $sentid is set to. To better explain, I have this lua code. (The lua code is working perfectly fine)
HS:PostAsync("http://examplesite0wwa/PresCand.php","sentid="..script.Parent.ExampleUser1.USERD.Value, 2)
And this sends as Variabel1 = Data1
And then I have this sql code.
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"]
$conn = new mysqli("localhost","anexapleomf1","","my_anexapleomf1");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_anexapleomf1`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = $sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>
And what this should be doing, is reading what ever the sent $sentid was, and
then setting the $sentid in WHERE, buuut it's not doing that.
An example of this would be if $sentid was sent with the value of 2, and then the
WHERE `President Candidates`.`id` = $sentid
would be read as
WHERE `President Candidates`.`id` = 2
You don't have any problem of reading the post variable in your code, try to echo the post variable to see if it has been posted effectively, if not, check out the action method of your form.
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