I am trying to use java-script prompt to insert values into MySQL. I have a html file and a php file.
The html files saved as Test.html:
<button onclick="myFunction()">Create Project</button>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project });
}
}
</script>
The conn.php:
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The conn.php works perfectly and inserts values if I remove the post parameter.
For example, instead of this:
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if i use:
$proj = "NewProject";
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
NewProject gets inserted into the database.
I am not sure if I am missing something in my index.html which is not posting the value in the prompt to php script. I have tried echo $_POST['project']; instead of inserting into MySQL. The echo is missing.
I have run your given code, it runs only i have added the jquery link above script code
Please check this correction,
<button onclick="myFunction()">Create Project</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project },function(response){
console.log(response);
});
}
}
</script>
and also i have added isset() function with $_POST param in conn.php file
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = isset($_POST['project'])?$_POST['project']:'';
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Related
I just want to change the text inside a p element dynamically instead of manually changing the content by opening the html file itself
You could try querying the text from a MySQL database. Here's a PoC:
Inside index.php you should have the code to query the DB and get your data.
index.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM htmldata WHERE element='pobject'"; #SQL SELECT query
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$pdata = $row['data'];
}
}
$conn->close();
?>
<html>
<body>
<p><?php echo $pdata; ?></p>
</body>
</html>
Now here's the PHP code for admin.php.
Note: This is only the code that will receive a POST parameter and insert it in the database. You should include session checking so unauthorized users cannot edit the p data, and also make a frontend that will send the POST request.
admin.php
<?php
if(!isset($_POST['pdata'])){
echo "No data passed";
}else{
$pdata = $_POST['pdata'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE htmldata SET data='$pdata' WHERE element='pobject'";
$result = $conn->query($sql);
$conn->close();
}
?>
I am creating a database to make my 'PHP' website but I couldn't do this. My website is cruzapp that is related to rideshare companies and changing it in to php to get details about our users. But I can't connect MYSQL by using the following PHP code:
?php
$username = "name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Not connected to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:"$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
$row{'year'}.<br>";
}
//close the connection
mysql_close($dbhandle)
?>
Can anyone help me to debug this code?
I will be very thankful to you.
Try this one out. It uses MySQLi with error echoing.
<?php
$username = "name";
$password = "password";
$hostname = "host";
$database = "examples";
$con = mysqli_connect($hostname, $username, $password, $database);
if (!$con) {
exit("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($con, "SELECT id, model,year FROM cars");
if (mysqli_error($con)) {
exit("Error: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($result)) {
echo "ID:" . $row['id'] . " Name:" . $row['model'] . "Year: " . $row['year'] . "<br>";
}
mysqli_close($con);
First of all you should not use mysql because with PHP 7 mysql extension does not work anymore. so you must consider to change it to mysqli or PDO. PDO is recommended. Any how for a quick fix $selected = mysql_select_db($dbhandle,"examples") do this and also check all your values like hostname database name table name and make sure there are no mistakes.
When I click on "subcribeButton" I want it to save the value and pass that value to my PHP file. I want that PHP file to then make a post to the SQL database.
This is my js:
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "save.php", { email: email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
This is my php code, I would like my php code to accept data from my js file and then post the data to my sql database:
<?php
$servername = "localhost";
$username = "user";
$password = "pw";
$dbname = "db_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
echo $text
$sql = "INSERT INTO MyGuests (email)
VALUES ($text)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The result is I'm getting the following error:
POST http://flockto.it/home/save.php 500 (Internal Server Error)
send # jquery.js:4
ajax # jquery.js:4
m.(anonymous function) # jquery.js:4
(anonymous function) # email.js:13
dispatch # jquery.js:3
r.handle # jquery.js:3
so why not adding a callback in your ajax request so you can debug it in console or with an alert see this it may help you
$.post( "save.php", { "email" : email } , function(result){
console.log(result);//here the result will display what you will echo after getting the post in your php file
});
so in your php file you can add this
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
//so if you check the console you will get the email
//value from your php file so then you can insert it at the DB as you want
You have a syntax error.
Your code is missing the ; at the end of this line:
echo $text
It should be:
echo $text;
The solution:
In the js file url was wrong and quotation marks around email were missing
$(".subscribeButton").on( "click", function() {
var email = $(".subscribeInput").val();
var isValid = isEmailValid(email);
if(isValid){
$(".errorMsg").css( "display", "none" );
modal.style.display = "block";
$.post( "data/save.php", { "email": email });
$(".subscribeInput").val("");
} else {
$(".errorMsg").css( "display", "initial" );
};
});
$(".subscribeInput").on( "click", function() {
$(".subscribeInput").val("");
});
In the php file used the wrong variable
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = $_POST['email'];
if (isset($_POST['email'])){
$text = $_POST['email'];
echo $text;
}
$sql = "INSERT INTO MyGuests (email)
VALUES ('$text')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
A million thanks to everyone who replied to this thread and helped me solve the issue.
I am trying to get data from a dropdown and post it to a textbox. But by some reason I dont get any response also the Error message that needs to be shown in the textbox.
First of all, this is my dropdown:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control' id='product1' name='product1' onChange='getProduct1(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["article_id"]. " | " . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
After selecting a item in the dropdown the scripts needs to paste . $row["name"]. into the following textbox:
<input type="text" class="form-control" id="product11" name="product11">
The jquery script that I am using to paste the name is the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getProduct1(selectedItem) { // Do an Ajax request to retrieve the information
console.log("getProduct1 before ajax", jQuery('#product1').val());
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: {'product1' : jQuery('#product1').val()},
success: function(response){
// and put the price in text field
console.log("getProduct1 after ajax", jQuery('#product1').val());
jQuery('#product11').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script uses the following PHP script that connects with the database and retrieves the relevant information:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$product1 = isset($_POST['produc1t'])?$_POST['product1']:'';
$product11 = isset($_POST['product11'])?$_POST['product11']:'';
$query = 'SELECT * FROM products WHERE id="' . mysqli_real_escape_string($conn, $product1) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['product11'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo "Error";
}
}
?>
When I run the script by selecting an option in the dropdown, nothing is happening. Does anyone know what is wrong with my script?
I am not sure you should query the database again for a value you already retrieved. Something like this should work:
jQuery( document ).ready(function() {
jQuery( "#product1" ).change(function(){
var name = jQuery( "#product1 option:selected" ).text().split('|')[1];
jQuery("#product11").val(name);
});
});
You don't need the javascript/jQuery command in the HTML
so I have a JavaScript function which calls to a PHP file using an asyncronous method. This is my code
JavaScript
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback (xmlHttp.responseText);
}
xmlHttp.open("GET", "http://127.0.0.1/formulario/insertReporte.php?"+'nombreAlumno='+nombreAlumno+'&noCta='+noCta+'&semestre='+semestre, true);
xmlHttp.send(null);
And here is my PHP File
<?php
$servername = "myServerName";
$username = "myUserName";
$password = "myPassWord";
$dbname = "myDb";
$nombreAlumno = $_GET['nombreAlumno'];
$noCta = intval($_GET['noCta']);
$semestre = intval($_GET['semestre']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ($nombreAlumno,$noCta,$semestre)";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
My issue comes on this line $nombreAlumno = $_GET['nombreAlumno']; as I get this error
On my database my nombreAlumno field is declared as a varchar.
I know my connection works because if I change that line into $nombreAlumno = intval($_GET['nombreAlumno']); it inserts 0 into my database.
Any ideas what am I doing wrong?
You need to add quotes around your values. Also use mysqli_real_escape_string before insert into database to prevent sql injection
$nombreAlumno=mysqli_real_escape_string($conn, $nombreAlumno);
$noCta=mysqli_real_escape_string($conn, $noCta);
$semestre=mysqli_real_escape_string($conn, $semestre);
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ('".$nombreAlumno."','".$noCta."','".$semestre."')";
Try this
<?php
$servername = "myServerName";
$username = "myUserName";
$password = "myPassWord";
$dbname = "myDb";
$nombreAlumno = $_GET['nombreAlumno'];
$noCta = intval($_GET['noCta']);
$semestre = intval($_GET['semestre']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ('".$nombreAlumno."','".$noCta."','".$semestre."')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>