I'm Not so good about PHP, I m still learning that language, so I have made Form which one will add data to mysql using PHP and Method POST. But in when i click on submit nothings happens in the database, no data added.
This is config.php
$SETTINGS["hostname"]='localhost';
$SETTINGS["mysql_user"]='username';
$SETTINGS["mysql_pass"]='passw';
$SETTINGS["mysql_database"]='database';
$SETTINGS["data_table"]='defaulttable'; // this is the default database name that we used
/* Connect to MySQL */
if (!isset($install) or $install != '1') {
$connection = mysql_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('Unable to connect to MySQL server.<br ><br >Please make sure your MySQL login details are correct.');
$db = mysql_select_db($SETTINGS["mysql_database"], $connection) or die ('request "Unable to select database."');
};
?>
and here is my HTML FORM
<form action="insert.php" method="post">
<li>Place Name: <input type="text" name="plname" /></li>
<li>City: <input type="text" name="plcity" /></li>
<li>Address: <input type="text" name="pladdress" /></li>
<li>Terminal QTY: <input type="number" name="plqty" /></li>
<li><input type="submit" name="save" value="Add Place" /></li>
And What About insert.php
<?php
include ("config.php");
$current_user = wp_get_current_user();
$UserID = $current_user->user_login ;
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
//$sql="INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('".$UserID."','".$_POST['plname']."','".$_POST['plcity']."','".$_POST['pladdress']."','".$_POST['plqty']."')";
$sql = "INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('{$UserID}','{$_POST['plname']}','{$_POST['plcity']}','{$_POST['pladdress']}','{$_POST['plqty']}')";
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
mysqli_close($connection);
?>
And when I klick to Button for add data, it does not works. No Errors, No Data updated or added in mysql database. What about Passwords, Host, Usernames, Table names etc... I Checked twice :( I would appreciate any helps from your side guys, Thanks in advance and SORRY FOR MY BAD ENGLISH
Your SQL query is not formatted properly. Try this:
$sql = "INSERT INTO wp_telemetry_place (plUserID, plName, plCity, plAddress, plTerminalQ) VALUES ('{$UserID}','{$_POST['plname']}','{$_POST['plcity']}','{$_POST['pladdress']}','{$_POST['plqty']}')";
Your query is probably giving you an error message, but you have a typo in your code, replace $conn with $connection to read it, like so:
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
Finally, and this is important, the way you're writing your code is hugely dangerous, because you're accepting user input without any filtering. I recommend you google SQL injection to learn more about it.
The main Problem was 'i' I changed
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);}
to
if (mysql_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error($connection);}
Now it works perfect, Just I need to look at SQL Injection thats all. Thank you guys anyway :))
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.
I'm trying to insert into my local sqlserver. The problem is that it doesnt seems to run php code. It opens page in browser with all my code:
Html
<!DOCTYPE html>
<html>
<head>
<title>Form linked to database</title>
</head>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="username">
<br>
Email: <input type="text" name="email">
<br>
<input type="submit" value="insert">
</form>
</body>
</html>
Php
<?php
$servername = "(local)\sqlexpress";
$username = "sa";
$password = "1234";
$dbname = "MyCalendar";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customermaster(code, name, email)
VALUES ('1234', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I'm begginer on this. Souldnt i take only the exception if something will go wrong?
You can not directly open php files. You need to install a local server on your computer for your php codes to be executed. Try XAMPP it is easy to install.
You need to first set up a web server. AppServ can recommend about it is simple and fast. Check the incoming POST when we come to your code.
Example :
if(extract($_POST)) {
$sql = "INSERT INTO customermaster(code, name, email) VALUES ('1234', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Also : After installation is complete in the url portion of the run, type http://localhost.
This project involves connecting to a database using phpMyAdmin. I have a file named index.php which presents the user with a simple form that connects to a file for processing called functions.php. I'm using WAMP to connect everything but when I try running everything the form and submit work but after the form is submitted the next page displays nothing when it should be displaying some information even if its an error message. I really can't figure out what's wrong. I've already created the database on phpMyAdmin by importing a file containing sql code to create all my tables for a relational database. Here is the code, any help is appreciated.
index.php
<form action="functions.php" method="post">
First Name: <input type = "text" name = "Fname"><br>
<!-- Last Name: <input type = "text" name = "Lname"><br>
Commision: <input type = "text" name = "commision"><br>
Phone Number: <input type = "text" name = "phone"><br>
Job Title: <input type = "text" name = "job"><br> -->
<input type="submit">
</form>
</body>
functions.php
<?php
$host = 'localhost';
$username = 'kempenaar';
$password = 'Jayson38!';
$db_name = '3660Project';
//$Fname = $_POST["Fname"];
echo "in the script";
$conn = mysql_connect($host, $username, $password,$db_name)
if(!$conn)
{
die ('Error connecting to MySQL server.' . mysql_error());
}
$db_select = mysql_select_db($db_name);
if(!$db_select)
{
die('Can\'t use ' . $db_name . ': ' . mysql_error());
}
$sql = "INSERT INTO Employee (First_Name, Last_Name, Commision, Phone_number, Job)
VALUES ($_POST["Fname"], $_POST["Lname"], $_POST["commision"], $_POST["phone"], $_POST["job"])";
if(mysql_query($sql)){
echo "Records inserted successfully.";
header('Location: http://localhost:8888/3660Project/');
} else{
echo "ERROR: Could not able to execute $sql. " . mysql_error($conn);
}
echo "made it here";
?>
A HTML form has been created that should (when filled) send the data it's holding to a database inserting a new row so it can be used later on. However, I can't seem to get it to work, I'm getting the following error:
Notice: Use of undefined constant con - assumed 'con' in C:\xampp\htdocs\form\insert.php on line 4
Warning: mysql_query() expects parameter 1 to be string, object given in C:\xampp\htdocs\form\insert.php on line 17
Data not inserted
HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Form linked to database</title>
</head>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="username">
<br>
Email: <input type="text" name="email">
<br>
<input type="submit" value="insert">
</form>
</body>
</html>
PHP Code
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!con) {
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')) {
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
$sql = "INSERT INTO person (Name,Email) VALUES ('$Name','$Email')";
if(!mysql_query($con,$sql)) {
echo 'Data not inserted';
} else {
echo 'Data inserted';
}
//header("refresh:2; url=form.html");
?>
I'm new to PHP and followed the following YouTube tutorial.
I'm also using XAMPP for this, on a localhost. Any help is appreciated. Thank you.
You should change:
if(!con){
echo 'Not connected to server!';
}
to:
if(!$con){
echo 'Not connected to server!';
}
as you're missing a dollar sign there.
Additionally, you're using a mysql_ function here, on the mysqli_ object $con:
if(!mysql_query($con,$sql))
Change this to
if(!mysqli_query($con,$sql))
SQL injection
As your query is vulnerable to SQL injection, then I'd like to recommend you take a look at using prepared statements, or using mysqli_real_escape_string()-- though, this comes with a few gotcha's: https://stackoverflow.com/a/12118602/7374549
You have done two small mistakes ie
1) forgot to add $ before the variable name ie changes is
if(!$con){
echo 'Not connected to server!';
}
2) you are connected with mysqli_connect but you are trying to use mysql_query functions in it. so please change and use mysqli_query
if(!mysqli_query($con,$sql)){ }
This is issue in your case. My suggestion is to use mysqli or PDO that is good practice.
You are not using the correct mySQL query function, you have used:
mysql_query($con
You should use:
mysqli_query
instead. Let me know if you still have issues.
Altough you have a lot of answers right now, I think none of those is the right one. I've written your code new, procedural as you did, but with prepared statements, so you're going to be save to SQL injections.
<?php
$con = mysqli_connect('localhost','[retracted]','[retracted]');
if(!$con){
echo 'Not connected to server!';
}
if(!mysqli_select_db($con,'tutorial')){
echo 'Database not selected!';
}
$Name = $_POST['username'];
$Email = $_POST['email'];
if ($stmt = mysqli_prepare($con, "INSERT INTO person (Name, Email) VALUES (?, ?"))) {
mysqli_stmt_bind_param($stmt, "ss", $Name, $Email);
mysqli_stmt_execute($stmt);
echo "Data inserted";
}
else {
echo "Error";
}
mysqli_close($con);
//header("refresh:2; url=form.html");
?>
I think it should work, if not let me know.
Try this :
<?php
// Create connection
$conn = new mysqli("localhost", "username", "password", "databasename");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('test fname', 'test lname', 'test#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<form action="insertresubmittedpaper.php" autocomplete="on" enctype="multipart/form-data" method="post">
<h1>Re-Submit Paper</h1>
<p>
<input type="file" name="uploaded_file"><br>
</p>
<br>
<br>
<center>
<p class="submit button">
<input type="submit" value="Submit">
</p>
</center>
</form>
Hello I'm working on a project where I need to insert a file into database, and after that I have an option where the user can update the existing file in database using a form and when once updated it will be redirected to another page.
I'm using PHP , mysql.
The Problem is a new file is not being updated into the database, but it is redirecting to another page.
Here i'm posting my code. Please suggest me necessary changes.
<?php
session_start();
if(isset($_SESSION['username']))
{
echo "<div id='User'>Welcome: " . $_SESSION['username'] . "</div>";
}
else
{
echo "<div id='Guest'>Welcome: Guest </div>";
}
/*
Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
*/
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
$link = mysqli_connect("localhost", "kuda", "secret", "researchcloud");
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$UserName=$_SESSION['username'];
$Subject = mysqli_real_escape_string($link, $_POST['subject']);
$Category = mysqli_real_escape_string($link, $_POST['category']);
$Journal = mysqli_real_escape_string($link, $_POST['journal']);
$mime = mysqli_real_escape_string($link, $_FILES['uploaded_file']['type']);
$data = mysqli_real_escape_string($link, file_get_contents($_FILES ['uploaded_file'] ['tmp_name'] ));
// attempt insert query execution
$sql = "UPDATE rc_ijai set FullPaper='$data', mime='$mime' where A1Email='$UserName' and Journal='$Journal'";
if(mysqli_query($link, $sql))
{
header('Location:authorprofile.php');
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
}
}
else {
echo 'An error occurred while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
?>
Don't use mysqli_query() to check that query has been executed or not. specially for insert and update queries. Because for update query some times a query will get executed and non of the row will get updated. So for insert and update check the number of rows affected after the query execution. After checking this You can easily solve it.