I want to be able to read the raw data from the URL path. The URL will look like:
https://newtest.000webhostapp.com/db.php?datainurl
The db.php is:
<?php
$postdata = file_get_contents("php://input");
$conn = new mysqli('localhost','2541','yhte','tg543');
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into cloud set rfid='.$postdata'";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
When I press enter in the URL the webpage echos: New record created successfully. I see the id in the database but the contents is not shown in the database.
Why the "datainurl" in the URL is not showing in the database?
The query string is available through $_SERVER['QUERY_STRING'].
php://input contains the request body.
Related
i want to make so my webpage takes values from a table in a database and displays them on the screen in the format that is shown below in the code, however i would then like to take the values for BikeID and ContactEmail and save them to session storage to be used on the update confirm page which your taken to when the update button is clicked. however the first issue is that the values wont save to the session storage and the second is that even if they did would the session get the correct value according to the Table/BikeID selected where the button is clicked. Image of the page layout after the code is run is below.
if anyone has any ideas i would be grateful.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username="Username"; // change this to your database username
$password="Password"; // change this to your database password
$database="Database"; // change this to your database username
$conn = new mysqli('localhost', $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tblBikeStolen, tblBike WHERE tblBike.BikeID=tblBikeStolen.BikeID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div id='UpdateTable'><table><tr><td> User No: " . $row["User"] . "</td>
<td>Bike ID: " . $row["BikeID"]. "</td><td> Contact: " . $row["ContactEmail"] . "</td></tr><tr><td>
Reported Time: " . $row["ReportTime"] . "</td><td> Address: " . $row["Address"] . "</td><td> Bike
MPN: " . $row["BikeMPN"] . "</td></tr><tr><td> Bike Brand: " . $row["BikeBrand"] . "</td><td> Bike
Model: " . $row["BikeModel"] . "</td><td> Bike Type: " . $row["BikeType"] . "</td><tr><td>
Investigation Notes: " . $row["UpdateNotes"] . "</td></tr><tr><td> Status: " . $row["Status"] . "
</td></tr><tr><form><button class='btn btn-primary btnUpdateInvest' type='submit'
value='Update'formaction='ConfirmUpdate.php' onClick='UpdateFunctionDAO.php'>Update</button></form>
</tr></table></div>";
$BikeID = $row['BikeID'];
$_SESSION["BikeID"] = $BikeID;
$ContactEmail = $row['ContactEmail'];
$_SESSION["ContactEmail"] = $ContactEmail;
}
} else { echo "0 results"; }
$conn->close();
?>
I recommend starting simple and then expanding your use case:
Instead of using formaction = 'ConfirmUpdate.php', try using formaction = 'ConfirmUpdate.php?bikeid=<your-bike-id>&contactemail=<the-contact-email>'
In ConfirmUpdate.php, check if $_GET['bikeid'] and $_GET['contactemail'] are set and valid. If you didn't get either of those keys or if they were invalid, write a meaningful error message on the screening instructing the user what to do next.
If you received both those keys and their values were reasonable, you can store them in a session for future processing. Once your processing is done, clear out that information from the session.
Your PHP code will look something like this:
echo "...value='Update' formaction='ConfirmUpdate.php?bikeid=" . $row["BikeID"] . "&contactemail=" . $row["ContactEmail"] . "' onClick='UpdateFunctionDAO.php'>...";
Try this and see how it works. You might have to do more work after this to ensure that the data you are publishing on the page is sanitized and not susceptible to injection.
Example
Let's say your initial page is called test.php and it looks like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$username=""; // change this to your database username
$password=""; // change this to your database password
$database=""; // change this to your database username
$conn = new mysqli('localhost', $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "your sql query";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
$displayText = sprintf('<div>Some other info. Bike ID is %s and contact is %s.</div>',
$row['bikeid'],
$row['contactemail']
);
$form = sprintf('
<form method="post" action="ConfirmUpdate.php">
<input type="hidden" name="bikeid" value="%s">
<input type="hidden" name="contactemail" value="%s">
%s
<input type="submit" value="Submit">
</form>',
$row['bikeid'],
$row['contactemail'],
$displayText
);
echo $form;
}
}
$conn->close();
?>
Result
Your ConfirmUpdate.php will look like this:
<?php
session_start();
$_SESSION['bikeid'] = $_POST['bikeid'];
$_SESSION['contactemail'] = $_POST['contactemail'];
echo sprintf('Received bike id %s and contact email %s',
$_SESSION['bikeid'],
$_SESSION['contactemail']
);
?>
When you click on the first button, you will be taken to ConfirmUpdate page, which will look like this:
Received bike id 1 and contact email test#gmail.com
When you click the 2nd button, you will see:
Received bike id 2 and contact email test#yahoo.com
Test this out on your own systems and you should be able to replicate this code in your project.
FOR ANYONE FOLLOWING ALONG SO FAR; I have gotten to the point where I have learned that my html page is making the request to open the php file but it isn't posting any data to it. If anyone knows what is wrong please let me know.
This is what I have on the front end so far.
stackVar.push([place.name, websiteName, place.rating, place.international_phone_number, place.id, place.formatted_address, place.types[0]]);
//code for saving to a file will go here
if(results.length == stackVar.length){
var request = new XMLHttpRequest();
request.open('POST', 'http://www.server.com/saveF.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(JSON.stringify(stackVar));
}
Okay so I have learned some things but I am still not quite there yet... Here is what I have as far as the php goes...
<?php $conn = new mysqli($sn, $un, $pw, $db);
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$bInfo = $_POST["stackVar"];
$infoEncoded = json_encode($bInfo);
$getsome = $infoEncoded[0][0];
$sql = "INSERT INTO companies(company) VALUES ('$getsome')";
echo $getsome;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close()
?>
I am playing around with php, i wish to make a simple api to save my name field in database using chrome postman
The is my php code:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type,x-prototype-version,x-requested-with');
header('Cache-Control: max-age=900');
header("Content-Type: application/json"); // tell client that we are sending json data
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$dxname =$_GET['name'];
$sql = "INSERT INTO crudtable(firstname, lastname, email,favjob)
VALUES ('".$dxname."', 'Doe', 'john#example.com','coder')";
if ($conn->query($sql) === TRUE) {
echo json_encode("New record created successfully");
// echo "New record created successfully";
} else {
echo json_encode("Some error");
// echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
When i am using postman ,
1. the name is not getting saved in db [only hard coded values are being saved]
2. I am not getting echo json_encode("New record created successfully"); once data is saved.
Please help, attaching screenshot of my postman result and how i am passing the name variable
Click here to see the image
You are sending data through post method and you are using GET.
Change:
$dxname =$_GET['name'];
To
$dxname =$_POST['name'];
ALso:
if ($conn->query($sql) === TRUE) {
To
if ($result = $conn->query($sql))
{ echo json_encode("New record created successfully");
// echo "New record created successfully";
} else {
echo json_encode("Some error");
// echo "Error: " . $sql . "<br>" . $conn->error;
}
Cannot query MySQL database via PHP
Json should be an array.. try this
echo json_encode(array("Success"));
where did you get the $_GET method? can you show us the html page? you can try using
$_POST['name'];
i am trying to capture some data from a IOT device. The problem isto capture the data you have to feed in the ip to the device so that data is [posted to that ip address.
To process the data,i came up with this script and aptly named it index.php
<?php
$servername = "94.049.947.776";
$username = "droid";
$password = "!#nord";
$dbname = "atree";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = $_POST;
$sql = "INSERT INTO gps (data)
VALUES ('$data')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
To test it out,i have this html page
<form method="post" action="972.245.119.017">
<input type="text" name="ed" value="jsonstring" />
<input type="submit" value="submit" />
</form>
However,no data is inserted to the database. What could be wrong with my script?.
$_POST is php variable in form of an Array, maybe try to :
replace :
$data = $_POST;
with :
$data = $_POST['ed']; // the value from the form
or some other value that you posted to the index.php like :
$data = $_POST['VALUE_NAME'];
consider working with PDO (http://php.net/manual/en/book.pdo.php) for the sql part
You should replace :
$data = $_POST;
by :
$data=$_POST['ed'];
I am writing a php file that takes values from a form and posts them to a mysql database. One of the table fields is a button link to a video that will play when clicked. It works great if I go into the database and manually add the link. However my PHP insert causes an error. Please have a look at this code:
$fileName = "video_".$id.".html";
$link = "<button class=\"count\">Watch Video</button>";
$con=mysqli_connect("localhost","videomanager","password","my_database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO video_list (date, title, description, link) VALUES('$_POST[date]','".mysqli_real_escape_string($_POST['sermon'])."','".mysqli_real_escape_string($_POST['description'])."','$link' )";
if (!mysqli_query($sql,$con))
{
die('Error: ' . mysqli_error());
}
echo "This video has been successfully added to the video database.";
mysqli_close($con);
If I look at $link by doing something like: echo $link; die(); it produces a page with the button and the code in the button looks good. Is it how I am trying to insert it? Thanks for your help!
you have a lot of errors
<?php
$fileName = "video_".$id.".html";
$link = "<button class=\"count\">Watch Video</button>";
$con = mysqli_connect("localhost","videomanager","password","my_database");
// Check connection
if ( mysqli_connect_errno() )
die('Failed to connect to MySQL: ' . mysqli_connect_error() );
// Check param is set
if( !isset($_POST['date'], $_POST['sermon'], $_POST['description']) )
die('Param Error');
// SQL Request
$sql = sprintf("INSERT INTO video_list (date, title, description, link) VALUES('%s','%s','%s','%s')",
mysqli_real_escape_string($con, $_POST['date']),
mysqli_real_escape_string($con, $_POST['sermon']),
mysqli_real_escape_string($con, $_POST['description']),
mysqli_real_escape_string($con, $link)
);
// SQL execute
$result = mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
// Free result
mysqli_free_result($result);
// Close connection
mysqli_close($con);
echo "This video has been successfully added to the Kim Watt videos.";