Reading $_POST variables - php

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.

Related

How to switch between two php scripts

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.

PHP sql insert code is returning false even when sql command if correct and database is too

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 . "')";

PHP script to Increment value in mysql

I am trying to design a scoreboard for a project for my local youth club and would like to be able to click a button onto a wordpress page that will run a PHP script to update a value by 1 in a sql db table, then i can grab the value and display it else where.
Not too worried about passwords being used in scripts at this will only be used within the local network that nobody else has access to, have looked around and found a few bits of code but im not able to actually get it working, here's what i've got so far.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "sot";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The database name is 'sot' the table i want to update is called 'wp_sotstats' and the field within the table is 'CaptainChest' i only need this to really work with just the one entry which the id is '1'
Any thoughts?
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
Is not creating record, it updating it. For me, I will take current value from database as Select, then do ++ to it and do Update query.
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
Please wrap it in quotes and finish statement with semicolon

show id of entered text to database

I'm fairly new to stack overflow. i am creating a site were you type text in to 2 text boxes and it sends it to a database. i need it then to tell me what the id of that was save it as a session and then upload it to another database. sounds confusing. but I'm stuck of one part. its viewing the result thats from just that user. i have tried just showing the the last id of the last uploaded but it can be very unreliable if multiple people are trying to upload data and know there exact session. I'm also having trouble linking the session with the id. below is the code for the forum saving to the database. I'm pretty confident with sending the id of that users inputed data to another database. I'm just stuck on finding that users inputed texts id and creating a session holding the id number
<?php
header("Location:myscorenum.php");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "score";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
session_start();
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "working";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
$value = $_POST['name'];
$value1 = $_POST['description'];
$sql = "INSERT INTO all_scores (name, description) VALUES ('$value','$value1')";
if ($conn->query($sql) === TRUE) {
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
ill have the processing to inset to another database in another file. I'm confident with uploading a specific session.
any questions don't hesitate to message me. thanks for your kind help.
You can use this:
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query
Like: echo $conn->insert_id;
Since you call it on $conn which is a mysqli instance that already has a connection, it will return your last inserted id, irregardless of other activities on the db (other queries do not affect the correctness of the output)
I edited my answer. This is the final part of your code and I've just added one line of code to it. Look if this is what you're looking for.
If this isn't working than make sure your database id field is AI.
if ($conn->query($sql) === TRUE) {
$id=$conn->insert_id; //this is where you get the last inserted id.
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
To use a session and set the ->insert_id to a session variable and use it in any other page, you can do this:
if ($conn->query($sql) === TRUE) {
session_start();
$_SESSION['id']=$conn->insert_id;
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
and now in any other page do this to retrieve the session variable:
session_start();
$id=$_SESSION['id'];
here you go and you get the id.
Are you still confused?

Php-Nothing being written in Mysql table using post method

I have looked online for many hours but still can’t figure out what’s wrong with my code. Code works okay when I have $SALES=30; $ID=10; etc. Now I want to post those values using html form, but can't make it to work.
<?php
$http_origin = $_SERVER['HTTP_ORIGIN'];
if ($http_origin == "http://......")
{
header('Access-Control-Allow-Origin: *');
}
$SALES = $_POST['SALES'];//Supplied by html form
$ID = $_POST['ID'];//Supplied by html form
$con = mysqli_connect("xxx","TABLE","xxx");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"xxxxxx") or die ("no database");
$sql="update TABLE
set
id = #newer := $ID,
tray_1 = case when tray_1 is null then #newer:=$SALES else tray_1 end,
tray_2 = case when #newer = $ID and tray_2 is null then #newer:=$SALES else tray_2 end,
tray_3 = case when #newer = $ID and tray_3 is null then #newer:=$SALES else tray_3 end
WHERE id = $ID";This updates table values where field is null
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
What is wrong with my code? Thank you.
There is probably some typo in first line:
$SALES = '$_POST['SALES']';//Supplied by html form
Should be:
$SALES = $_POST['SALES'];//Supplied by html form
Maybe this will help you?
BTW you should check something about mysql injection, for example here:
PHP MySQL injection example?
Handling forms this way is ultra dangerous, because anyone can delete whole your database in one second.

Categories