Although I found other topics reporting the same issue, none of them helped me.
I'm learning AngularJS and I tried to insert data into a MySQL database. I have a really simple HTML file where the user can provide a name and age, and then click in a Submit button which would put this data into the MySQL database.
Since it's just for learning purposes, I named the database and the table "test".
I am using PHP as the server language.
I have:
- An index.html file for the view
- A script.js file where I use AngularJS HTTP POST method to insert data into the MySQL database
- A config.php file where I deal with the connection with the server and the insertion of data into the database.
Also, my table consists of only 3 columns: an ID (unique, auto-incremented), a "name"(text) and an "age"(int).
The code for each file is here:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AngularJS-PHP-MySQL</title>
<!-- AngularJS CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<!-- script.js with implementation of Module and Controller -->
<script src="script.js" ></script>
</head>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form id="myForm" action="" method="post">
<input type="text" name="name" id="name" value="" placeholder="Name" ng-model="nameModel">
<input type="text" name="age" id="age" value="" placeholder="Age" ng-model="ageModel">
<input type="button" name="sub" id="sub" value="Submit" ng-click="insertData()">
</form>
</div>
</body>
</html>
script.js
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http){
$scope.insertData = function(){
$http.post("config.php",{'name': $scope.nameModel, 'age': $scope.ageModel})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
}
});
config.php
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$Table_name = "test";
mysql_connect($servername, $username, $password);
mysql_select_db($Table_name) or die(mysql_error());
$name = $_POST['name'];
$age = $_POST['age'];
mysql_query("INSERT INTO $Table_name('name', 'age') VALUES('$name', '$age')");
?>
I get an alert that the POST method was successful but it did not insert the data into the table. I have no idea why and I don't find an answer online.
I found in another topic here that AngularJS and some server side languages like PHP have different ways to serialize and transmit the data. Like the post says, the problem lies with PHP being unable to understand AngularJS’s transmission natively.
To avoid that, I explicitly built the header on my inserData() function:
script.js
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http){
$scope.insertData = function(){
var request = $http({
method: "post",
url: "config.php",
data: {
name: $scope.nameModel,
age: $scope.ageModel,
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
});
I also changed my config.php file into:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "test";
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
$age = $request->age;
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO test(name, age) VALUES('$name', '$age')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Now they can transmit compatible data. I also assigned the connection to a variable and then used it to query my data.
The HTML remains the same. With these changes, everything here is working properly now.
I'm not sure if your PHP/MYSQL code is OK.
Could you try the following code?
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$Table_name = "test";
$connection = mysql_connect($servername, $username, $password);
mysql_select_db($Table_name, $connection) or die(mysql_error());
$name = $_POST['name'];
$age = $_POST['age'];
$sqlQuery = "INSERT INTO $Table_name('name', 'age') VALUES('$name', '$age')";
mysql_query($sqlQuery, $connection);
?>
Related
Sorry for the newbie question, but I have this task which kind of got me stuck.
So, I made a database in PhpMyAdmin, created a table with data : Products(id, name, city) and created a stored procedure that will actually do a query on the table to find out the product with a certain name (which will be input-ed by the user on the web page). My stored procedure is: proc_test and takes one VARCHAR paramter.
So, how can I do this in a php script? How can i ask the user for some data, (on the site he should have like a box to type it) then click a search button, and get redirected to the page with the query results. This is my code so far:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CALL proc_test('pencil');";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['numec'] . "<br/>";
}
}
$conn->close();
?>
Here, of course, I manually give the parameter in the script. But I don't know how to change this and ask for a user input instead. Any help is welcome!
You can use ajax to send the data from your website to the php file where you can search for it in the database and send that data back to the user. In my example, the data is being displayed on the same webpage. You could echo the link to the website and redirect the user on the webpage using JavaScript if you really wanted to but my example is just a proof of concept.
index.html
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input required type="text" id="user_input">
<button onclick="sendData()">Search</button>
<p id="result"></p>
<script>
function sendData() {
var var_params = $('#user_input').val();
$.post('test.php', {params: var_params}, function(data) {
document.getElementById('result').innerHTML = "Your search result: " + data;
});
}
</script>
</body>
</html>
test.php
<?php
if(isset($_POST['params'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$param = mysqli_real_escape_string($conn, $_POST['params']);
$sql = "CALL proc_test('$param');";
if($result = mysqli_query($conn, $sql)) {
while($row=mysqli_fetch_assoc($result)) {
echo $row['numec']. "<br/>";
}
}
$conn->close();
}
?>
I created this for one of my projects. We have a webshop where users can enter their credentials and order products. The current solution puts all the data into a .csv-file and I was tasked with creating a mysql database as a new solution.
I added a simple HTML insert for the user to enter his name, but if I try to run the script I get a syntax error for line 19. I'm new to programming and therefore not sure what the error is here.
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "localhost";
$password = "";
$dbname = "test"
// create a variable
$Vorname=$_POST['Vorname'];
$Nachname=$_POST['Nachname'];
//Execute the query
mysqli_query($connect "INSERT INTO tbl_bestellungen(Vorname,Nachname)
VALUES('$Vorname','$Nachname')");
<?php include 'database.php';>
if(mysqli_affected_rows($connect) > 0){
echo "<p>Bestellung erfasst</p>";
} else {
echo "Bestellvorgang fehlgeschlagen<br />";
echo mysqli_error ($connect);
<h2>Text Input</h2>
<form>
Vorname:<br>
<input type="text" name="Vorname">
<br>
Nachname:<br>
<input type="text" name="Nachname">
<input type="submit" name="button1" value="Senden">
</form>
</body>
</html>
Thanks in advance.
Well you should do like this way:
$servername = "localhost";
$username = "localhost";
$password = "";
$dbname = "test"
$dbConn = mysqli_connect($servername, $username, $password, $dbname);
if(!$dbConn){
echo "No Db connected";
}
//above connection code should be in a separate file and include in all files or header
$Vorname=$_POST['Vorname'];
$Nachname=$_POST['Nachname'];
$query = "INSERT INTO tbl_bestellungen (Vorname,Nachname)
VALUES('$Vorname','$Nachname')";
or you can set query like
$query = "INSERT INTO tbl_bestellungen (Vorname,Nachname)
VALUES('".$Vorname."','".$Nachname."')";
if($dbConn->query($query)){
echo "Record inserted !";
}else{
echo "Record cannot be inserted !";
}
I am trying to save a form data into my database but I get just empty records.
I tryied many solutions but I really don't know where's the bug. I am getting crazy!
This is my form:
<head>
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit">
</form>
And this is my PHP script to save records:
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysqli_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysqli_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysqli_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysqli_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysqli_real_escape_string(htmlspecialchars($_POST['status']));
}
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO exposition (name, author, description, misure, date, status)
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
And this is what I get in my database at the moment:
First, you are mixing the mysql api's at somepoint you are using mysqli_* at some point u using mysql_* They don't mix. And mysql_* functions are depreciated they no longer supported by later versions of php. better use mysqli or pdo. this mysql_real_escape_string() or mysqlo_real_escape_string() is not safe enough to prevent you against sql injections. solution is simple better start using mysqli prepared statements or pdo prepared statements.
another error : <input type="text" name="name"> <input type="text" name="name"> these two inputs fields have the same name attribute php will only read one. and you will get an undefined index here $misure = $_POST['misure']; You need to activate error reporting while you are still developing so you can see your errors and notices:
add this at the top of every php page : ini_set('display_errors', 1);
error_reporting(E_ALL);
also date date is a reserved word for mysql so you better use something else for your column name or add backslashes date
Oh and your code never execute here :
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysql_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysql_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysql_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
}
Why is that? because you do not have POST value with the submit attribute name. <input type="submit"> see? your submit does not have a name attribute. therefore. This means
all this :
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')"; These are all undefined variables. I'm surprised why doesn't your server tell you that, with that error reporting enable you will get all those.
This is what u need to do to solve that :
Your html side.
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit" name="submit">
</form>
uploadall.php
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$sql = $conn->prepare("INSERT INTO exposition (name, author, description, misure, date, status)
VALUES (?,?,?,?,?,?)");
$sql->bind_param("ssssss", $name, $author, $description, $misure, $date);
if ($sql->execute()) {
echo "New record created successfully";
} else {
//you have an error
}
$conn->close();
}
?>
That's all good luck.
Update :
I corrected errors you told me and I am using PDO now but it still
doesn't work
I read that from your comments above, but you not telling us what the errors are, but I believe they are the ones I highlighted above.
with PDO this is how u will achieve your goal :
<?php
//connection
$servername = 'XXXXXXXXXXXXX';
$dbname = 'XXXXXXXXXXXXX';
$username = 'XXXXXXXXXXXXXX';
$password = 'XXXXXXXXX';
$charset = 'utf8';
$dsn = "mysql:host=$servername;dbname=$dbname;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $username, $password, $opt);
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$stmt = $dbh->prepare("INSERT INTO exposition (name, author, description, misure, date, status)VALUES (?,?,?,?,?,?)");
if ($stmt->execute(array($name,$author,$description,$misure,$date,$status))) {
echo "New Record inserted success";
}
}
?>
Variable name problem E.g
Name: <input name="name">
and :
Misure: <input name="name">.This must be different.
Again, <input type="submit"> should be <input type="submit" name="submit">.
Hope, it will be helpful.
The variables you are using inside your INSERT Query are out of scope from the first if block where you are getting the data from your form. If the variables are initialized before the first if block it might work. like below..
$name = ""; $author = "";$description = "";$misure = "";$date = "";$status=";
if (isset($_POST['submit'])){ // as is}
I'm not sure if this is a duplicate question due to the fact that I'm not even sure how to properly form it (That's why the title of this question makes no real sense). I am beginning to learn PHP so I can utilize SQL databases in my webpages.
My question is, how would I be able to make it so a user types in a password into an input box, which is then used by a PHP script as the password to a MySQL login to display the contents of a table in an HTML table? Now, I have most of this figured out, the only problem is displaying the table on the same page which the password is entered and the submit button is hit. Would I need to use AJAX? Because I don't know the first thing about it. Here is what I have so far:
Index.php:
<DOCTYPE! html>
<html>
<head>
<title>Guy's Random Project</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="scripts.js"></script>
</head>
<body>
<div>
<form action="" method="POST">
<font size="4">Password: </font><input type="text" id="pass" name="pass"/><br>
<input class="buttonGreen" type="submit" value="Submit" id="1" onMouseDown="mouseDown(1)" onMouseOut="mouseUp(1)"/>
</form>
</div>
<table><thead><th>ID</th><th>Name</th><th>Type</th><th>Rating</th></thead><tbody>
<?php include 'getTableData.php'?>
</tbody></table>
</body>
</html>
getTableData.php:
<?php
$servername = "localhost";
$username = "root";
$password = $_POST['pass'];;
$dbname = "testing";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, type, rating FROM crap_food";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"] . "</td><td>" . $row["name"] . "</td><td>" . $row["type"] . "</td><td>" . $row["rating"] . "</td></tr>";
}
} else {
}
$conn->close();
?>
I understand the fact that PHP is run server side, and is only run before any HTML is read by the client, so making a function run when a button is hit wouldn't exactly be possible just using PHP and HTML, but this would be similar to what I'm looking for. I don't want to redirect the user to another page via the form action (Which is why it's blank), I want to keep this all within index.php. Thanks (And sorry for the horrible forming of this question, I'm just a bit confused).
You Use AJAX for this.
$.ajax({
url: 'xxx.php',
data:formData,
cache: false,
contentType:false,
processData:false,
type: 'post',
success: function(response)
{
//do something
}
try this :
$password =$_POST['pass'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username,$password);
$sql = 'SELECT firstname FROM users';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
while ($r = $q->fetch()):
echo ($r['firstname']);
echo "<tr><td>" . ($r['firstname']) . "</td></tr>";
endwhile;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" .$pe->getMessage());
}
?>
I am trying to make a functionality where I am sending Name and Age using ajax. The same is gathered by PHP and then stored to DB. I think I am doing it correctly but data not saved in database. Can someone help me out?
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function(){
$.ajax({
url: 'addData.php',
type: 'POST',
dataType: "json",
data: {
name: $('#name').val(),
age: $('#age').val(),
}
})
});
});
</script>
</head>
<body>
<input id="name" type="text" />
<input id="age" type="text" />
<button>Click</button>
</body>
</html>
PHP
<?php
//Parameters for connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test1";
//Reading json
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$name = $data_back->{"name"};
$age = $data_back->{"age"};
// Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Creating Query
$sql = "INSERT INTO table1 (name, age) VALUES ($name, $age)";
//Running Query
$conn->query($sql);
//Closing Connection
$conn->close();
?>
ERROR
Even though you're sending data with jquery as json, php is still recieving it as a $_POST object. So, this should work:
$name = $_POST['name'];
$age = $_POST['age'];
I think your object $data_back is empty because of errors in parsing of data by function json_decode. You should try to use var_dump($data_back); exit; after json_decode or more advanced methods such as debugging.
I believe this is the proper way to access data post json_decode
$name = $data_back->name;
I also recommend looking into prepared statements for the database query execution...Ok, I HIGHLY recommend you look into it.
Edit: Maybe try this as well: Replace file_get_contents() with $_POST;