So i'm trying to execute a Insert Statement using PHP, but when i call the part of the code that should do it, nothing happends...
Already checked it up to see what's going wrong, but could't find out.
Here's the JavaScript function that calls the PHP code.
function comparaSenhas(){
var pass = document.getElementById("pwd1").value;
var pass2 = document.getElementById("pwd2").value;
if(pass !== pass2){
return false;
}else{
return true;
}
}
function postData(){
var hr = new XMLHttpRequest();
var url = "../mysql.php";
var fstnm = document.getElementById("fn").value;
var lstnm = document.getElementById("ln").value;
var dtnasc = document.getElementById("dn").value;
var email = document.getElementById("em").value;
var senha = document.getElementById("pwd1").value;
var vars = "fname="+fstnm+"&lname="+lstnm+"&dt_nasc="+dtnasc+"&email="+email+"&senha="+senha;
if(comparaSenhas()){
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
alert(return_data);
}
}
hr.send(vars);
}
}
And here's the PHP code that i'm using.
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "godienski";
$dbname = "web";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("insert into usuarios(first_name, last_name, data_nascimento, email, senha) values (?,?,?,?,?);");
$stmt->bind_param("sssss",$firstname,$lastname,$dtnascimento,$mail,$password);
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$dtnascimento = $_POST['dt_nasc'];
$mail = $_POST['email'];
$password = $_POST['senha'];
$stmt->execute();
$stmt->close();
$conn->close();
?>
</body>
</html>
Can anyone help?
Related
I've been trying to get data from my database into a table on my website using js/php but I can't get the php to give a valid xml to the script.
This is the php code:
<?php
$serverName = "localhost";
$userName = "***";
$password = "***";
$DBName = "DataBase1";
// Connect to DB
$connection = mysqli_connect($serverName, $userName, $password, $DBName);
if (!$connection)
{
die("Connection failed: " . mysqli_connect_error());
} else {
//echo "Connected to DB<br>";
}
// Collect data
$selectionSD = $connection->query("SELECT * FROM `SensorData`");
$selectionSL = $connection->query("SELECT * FROM `SensorLog`");
// Generating XML file
//$xmlSD = new XMLWriter();
//$xmlSD->openUri("php://output");
//$xmlSD->startDocument();
//$xmlSD->setIndent(true);
//$xmlSD->startElement("SensorDataTable");
//while ($row = mysqli_fetch_assoc($selectionSD))
//{
// $xmlSD->startElement("SensorData");
// $xmlSD->startElement("ID");
// $xmlSD->writeRaw($row["ID"]);
// $xmlSD->endElement();
// $xmlSD->startElement("SID");
// $xmlSD->writeRaw($row["SID"]);
// $xmlSD->endElement();
// $xmlSD->startElement("Value");
// $xmlSD->writeRaw($row["Value"]);
// $xmlSD->endElement();
// $xmlSD->startElement("Comment");
// $xmlSD->writeRaw($row["Comment"]);
// $xmlSD->endElement();
// $xmlSD->startElement("DateTime");
// $xmlSD->writeRaw($row["DateTime"]);
// $xmlSD->endElement();
// $xmlSD->endElement();
//}
//$xmlSD->endElement();
//header("Content-type: text/xml");
//$xmlSD->flush();
//$xmlSD->endDocument();
// Test code
$document = new DOMDocument('1.0', 'utf-8');
$document->formatOutput = true;
$root = $document->createElement('SensorDataTable');
$root = $document->appendChild($root);
while ($row = mysqli_fetch_assoc($selectionSD))
{
$node = $document->createElement('SensorData');
$node = $root->appendChild($node);
// ID
$dataNode = $document->createElement('ID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["ID"]);
$data = $dataNode->appendChild($data);
// SID
$dataNode = $document->createElement('SID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["SID"]);
$data = $dataNode->appendChild($data);
// Value
$dataNode = $document->createElement('Value');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Value"]);
$data = $dataNode->appendChild($data);
// Comment
$dataNode = $document->createElement('Comment');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Comment"]);
$data = $dataNode->appendChild($data);
// DateTime
$dataNode = $document->createElement('DateTime');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["DateTime"]);
$data = $dataNode->appendChild($data);
}
echo $document->saveXML();
// Close DB connection
$connection->close();
?>
I've tried to generate the xml a different way but no luck (the commented lines was what I tried first).
To get the xml into a table I use js with this code:
console.log(xml);
let i;
const xmlDoc = xml.responseXML;
if (xmlDoc === null) {
console.log("Failed to get response.");
}
let table = "<tr><th>SID</th><th>Value</th></tr>";
const x = xmlDoc.getElementsByTagName("SensorData");
for (i = 0; i < x.length; i++) {
table += "<tr><td class='center'>" +
x[i].getElementsByTagName("SID")[0].childNodes[0].nodeValue +
"</td><td class='center'>" +
x[i].getElementsByTagName("Value")[0].childNodes[0].nodeValue +
"</td></tr>";
}
console.log("Changing DB display");
document.getElementById("DB").innerHTML = table;
Where xml = the path to the php file.
When trying to run this it gives an error that xmlDoc is null. If I run this using an actual xml file on my drive it works fine.
If I call the php file directly and inspect the source it shows this:
<?xml version="1.0" encoding="utf-8"?>
<SensorDataTable>
<SensorData>
<ID>1</ID>
<SID>1</SID>
<Value>19.50</Value>
<Comment>DHT_Temp</Comment>
<DateTime>2021-10-04 12:57:51</DateTime>
</SensorData>
<SensorData>
<ID>2</ID>
<SID>2</SID>
<Value>57.50</Value>
<Comment>DHT_Humi</Comment>
<DateTime>2021-10-04 12:57:55</DateTime>
</SensorData>
<SensorData>
<ID>3</ID>
<SID>1</SID>
<Value>19.60</Value>
<Comment>DHT_Temp</Comment>
<DateTime>2021-10-04 12:58:29</DateTime>
</SensorData>
<SensorData>
<ID>4</ID>
<SID>2</SID>
<Value>57.20</Value>
<Comment>DHT_Humi</Comment>
<DateTime>2021-10-04 12:58:32</DateTime>
</SensorData>
</SensorDataTable>
How can I fix this issue, I’ve searched the web but the solutions I've come across did not work (creating the xml in a different way for example).
Fixed: change in the php code, added header("Content-type: text/xml"); back:
<?php
$serverName = "localhost";
$userName = "***";
$password = "***";
$DBName = "LIDAc";
// Connect to DB
$connection = mysqli_connect($serverName, $userName, $password, $DBName);
if (!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}
// Collect data
$selectionSD = $connection->query("SELECT * FROM `SensorData`");
$selectionSL = $connection->query("SELECT * FROM `SensorLog`");
// Generate XML file
$document = new DOMDocument('1.0', 'utf-8');
$document->formatOutput = true;
$root = $document->createElement('SensorDataTable');
$root = $document->appendChild($root);
while ($row = mysqli_fetch_assoc($selectionSD))
{
$node = $document->createElement('SensorData');
$node = $root->appendChild($node);
// ID
$dataNode = $document->createElement('ID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["ID"]);
$data = $dataNode->appendChild($data);
// SID
$dataNode = $document->createElement('SID');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["SID"]);
$data = $dataNode->appendChild($data);
// Value
$dataNode = $document->createElement('Value');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Value"]);
$data = $dataNode->appendChild($data);
// Comment
$dataNode = $document->createElement('Comment');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["Comment"]);
$data = $dataNode->appendChild($data);
// DateTime
$dataNode = $document->createElement('DateTime');
$dataNode = $node->appendChild($dataNode);
$data = $document->createTextNode($row["DateTime"]);
$data = $dataNode->appendChild($data);
}
header("Content-type: text/xml");
echo $document->saveXML();
// Close DB connection
$connection->close();
?>
I have function that is running multiple times and executing a PHP file. I do, however, want to make sure the functions does not interfere with each other.
for(int i = 0; i<5; i++){
functionName(i)
}
function functionName(number){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
var PageToSendTo = "phpFile.php?";
var MyVariable = number;
var VariablePlaceholder = "name=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xhttp.open("GET", UrlToSend, true);
xhttp.send();
}
This is how my code looks so far, how do I change it so that the next iteration of the function does not effect the previous one?
phpFile.php
<?php
require '../notWebsite/dbh.php';
session_start();
$variable = $_GET['name'];
$sqlInsertClass = "INSERT INTO class (className) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqlInsertClass)) {
header("Location: ../Website.php?error=InsertError");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $variable);
mysqli_stmt_execute($stmt);
exit();
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
hye.. im trying to create a quiz game but now im stuck and already spend hours to try transferring local storage data into database but still the data can't be recorded in database.
this is my js code:
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
$('input[type="text"]').each(function(){
var id = $(this).attr('id');
var score = $(this).val();
localStorage.setItem(id, score);
});
location.href = "wheel2.html";
});
then, to show collected marks:
function displayScore() {
var score = $('<p>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect+=10;
}
}
score.append('You got ' + numCorrect + ' marks!! ');
return score;
}
im also already try to use this code:
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "marks" + score;
xhr.open("POST", "marks.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
this is my php code:
<?php
//provide your hostname, username and dbname
$host = "localhost";
$user = "root";
$password = "";
$dbname = "test1";
$conn = new mysqli($host, $user, $password, $dbname);
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$sql = "INSERT INTO participant (marks)
VALUES ('".$_POST['marks']."')";
{
echo"<script>alert('successfully registered')</script>".' back ';
header('location:wheel.html?message=success');
}
?>
I am sending some information to a php file that runs a query but I want to also retrieve some information from that php file at the same time. The php file executes fine but I can't get the json_encoded object.
Javascript function that sends a string and a number to a php file:
function open_close(){
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status="+status+"&TicketNum="+ticketNum;
var http3 = createAjaxRequestObject();
if (http3.readyState == 4) {
if (http3.status == 200){
alert("Ticket Updated!"); //This never gets hit
getUpdatedTicket(JSON.parse(http3.responseText));
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
PHP File that takes the string and number and updates a table
<?php
include("config.php");
session_start();
$status = $_POST["Status"];
$num = $_POST["TicketNum"];
$newStatus = " ";
if(strcmp($status, "Open") == 0){
$newStatus = "Closed";
}
elseif(strcmp($status, "Closed") == 0){
$newStatus = "Open";
}
$sql = "UPDATE tickets SET Status = \"$newStatus\" where TicketNum = $num ";
$r = $conn ->query($sql) or trigger_error($conn->error."[$sql]");
$sql = "SELECT * FROM tickets where TicketNum = $num";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
?>
How can I retrieve the json_encoded object in the same javascript function?
You'd need a readyState listener to know when the request is done, and then get the data from the responseText
function open_close() {
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status=" + status + "&TicketNum=" + ticketNum;
var http3 = createAjaxRequestObject();
http3.onreadystatechange = function () {
if (http3.readyState == 4) {
if (http3.status == 200) {
console.log(http3.responseText); // <- it's there
}
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
I want to add Google captcha to my php form. The form adds data to my mysql database. How can I add the two parts of code together so the form checks first the captcha and after it's checked, then send it.
$servername = "";
$username = "";
$password = "";
$database = "";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = $_SESSION['userName'];
$contact = $_POST['naar'];
$address = $_POST['bericht'];
$sql = "INSERT INTO messages (to_user, from_user, message)
VALUES ('".$contact."', '".$email."', '".$address."')";
$conn->close();
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "xxxxxxxxxxxxxx";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true)
{
echo "Logged In Successfully";
}
else
{
echo "You are a robot";
}
}
As #Dagon and #Marc B have suggested in the comments above, try this:
$servername = "";
$username = "";
$password = "";
$database = "";
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//form submitted
//check if other form details are correct
//verify captcha
$recaptcha_secret = "xxxxxxxxxxxxxx";
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
$response = json_decode($response, true);
if($response["success"] === true)
{
//$conn = new mysqli($servername, $username, $password, $database);
try{
$db = new PDO('mysql:host='.$servername.';dbname='.$database,$username,$password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Error connecting to DB";
echo $e->getMessage();
exit();
}
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$email = $_SESSION['userName'];
$contact = $_POST['naar'];
$address = $_POST['bericht'];
$sql_pdo = "INSERT INTO messages (to_user, from_user, message)
VALUES (:contact, :email, :address)";
$stmt = $conn->prepare($sql_pdo);
try {
$result = $stmt->execute( array(
':contact' => $contact,
':email' => $email,
':address' => $address
));
if ( count($result) > 0 ) {
// Insert has gone well. Do your things here.
echo "Logged In Successfully";
}
else {
// Insert error. Report, check, ...
}
}
catch(PDOException $e){
echo 'could not insert in DB';
echo 'Error: ' . $e->getMessage();
return false;
}
$conn->close();
}
else
{
echo "You are a robot";
}
}