I built an html page with some options to insert details for a friends club.
I used an INSERT query and it worked. I want to add other queries like an UPDATE, DELETE, SELECT etc.
this is the php file:
<?php
//Input posted data.
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
$Date = $_POST["Date"];
$Mail = $_POST["Mail"];
$Pass = $_POST["Pass"];
// Create connection
$conn = mysqli_connect('localhost','root',"");
//Check if the connection was opened, if not prompt the error to the page.
if (!$conn)
{
die('Could not connect: ' . mysqli_error());
}
//Select the data base.
mysqli_select_db($conn, "club");
//Set the character set to utf-8 to allow hebrew.
mysqli_query($conn, "SET NAMES 'utf8'");
//SQL query - user Details
$sql = "INSERT INTO customers (Fname, Lname, Mail, Date, Pass)
VALUES('$Fname','$Lname','$Mail','$Date','$Pass')";
//Run SQL query
$results = mysqli_query($conn, $sql) or die (mysqli_connect_errno());
//Close the SQL connection.
mysqli_close($conn);
?>
I want to use those queries in the same file.
how can I do that?
Should I add a new form on the same page?
For example <form name="input" action="Update.php" method="POST"> to direct it to the Update.php file?
can I use more than one form at the same html file?
I've created this form for the Update button on the page to Update.php file but it doesn't work. It just adds the details and does not update them, although I used the UPDATE query.
You take all your PHP code and put it in the head of the form's page, then wrap it all inside
if(isset($_POST['submit-button-name'])){
//YOUR PHP CODE
}
Now you for each submit-button-name you make an if statement with it, for example
if(isset($_POST['insert'])){
//YOUR INSERT QUERY
}
if(isset($_POST['update'])){
//YOUR UPDATE QUERY
}
if(isset($_POST['delete'])){
//YOUR DELETE QUERY
}
That if you for example have 3 buttons like the following
<button type='submit' name='insert'>INSERT</button>
<button type='submit' name='update'>UPDATE</button>
<button type='submit' name='delete'>DELETE</button>
Inside the form, of course the UPDATE & DELETE queries require an identifier to find the row
WHERE id = $id
So it depends how you will implement the buttons in one form.
Related
I am trying to delete a record from my database when I press the submit button (input with type of submit) but this code is not working and I can't figure out why.
Here is the button code:
<input type="submit" value="Delete Selected Weapon" class="mybutton" name="Submit">
Here is the PHP code:
<?php
if(isset($_POST['Submit']))
{
require_once('../connect.php');
$selected = $_POST['deleteweaponname'];
$sql = "DELETE FROM weapon WHERE weaponname = $selected";
$result = $connect -> query($sql);
if(!$result)
{
echo "Could not delete record";
}
$connect -> close();
}
?>
The $selected variable is supposed to get the value of a select
I don't receive my error message either, when I press the button it just refreshes the site as if there were no PHP code attached to the button.
I also know that my connect.php is working because in another file it works.
I also tried isset($_POST['submit']) but that didn't work either.
I tried putting the code at the end of the file, and now it's in the front of it but neither seems to work.
The simple solution is quote string value:
$sql = "DELETE FROM weapon WHERE weaponname = '$selected'";
But this solution is open to SQL injection. So best way is using prepared statements:
-- set placeholder for variable
$sql = "DELETE FROM weapon WHERE weaponname = ?";
-- prepare statement
$stmt = $connect->prepare($query);
-- execute statement using variable
$stmt->execute([$selected]);
So, I have a form with some field in my page. For example - auth.php. The data in fields of this form recieved by calling some php function, that gives this data from MySQL DB. The code:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
The data inserting in fields by this code:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
But how to realize mechanism of insertion some entry to my MySQL DB. For example, user pressed the ADD button on my Form, fill the field "Name" by his own data and press SAVE button - i want to save this user data directly in my MySQL DB.
Please help!
To achieve this, you'll need to follow a few steps:
create the html form
form.html
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
create submit page
submit.php
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
Now you should be able to have your data in database.
Please have a look at this example on how to connect to database http://docs.kisphp.net/database-connect/
Instead of mysqli you may/should use PDO.
P.S.
In your code:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
Is always a good practice to follow some principles:
function names starts with lowercase
class names starts with uppercase
do not use ?> in php files that contains only PHP code
indentation of all code is not necessary.
and so on.
you may find here more details http://www.php-fig.org/psr/psr-2/
P.P.S.
This is basic usage. Once you understand the principle you can extend it to ajax. Create an ajax function that will submit the form data to submit.php file.
I'm new to PHP and am trying to build my a website to display information on TV shows stored in a MySQL DB. I've currently got a webpage that will create a table to display the information in the DB, however I'd like each row to link to a dynamically populated page with more info on each show (also pulling from the DB). My question is how do I get the site to know which link has been clicked and then save that as a variable so it can then be recalled on a new to populate the correct information?
I'm currently using this to populate the page.
<!--Populate page with data from SQL-->
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "media_server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th></th><th></th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>
<img src='../images/thumbnails/tv/".$row["thumbnail_path"]."'>
</td>
<td class='td_title'>
<a href='#' onclick='show_var_set();'>".$row["show_title"]."</a>
</td>
<td class='td_desc'>".$row["show_desc"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "Error - 0 results were returned my the database. Please try again.";
}
$conn->close();
?>
One option is to change your href links to point to this page and pass a GET variable you can retreive. The added bonus to this approach is you could bookmark a particular show and come back to that page, since the bookmark will include that GET variable.
So you could change your links to something like this:
echo '', $row['show_title'],'';
Then you'd retrieve that variable by testing for, then reading the GET variable and performing a db query to populate the page with that show's data.
Here's how you'd test for and retreive that variable:
if (isset($_GET['show']))
{
$show = $_GET['show'];
// Perform database lookup using $show
}
Remember to never put user input directly into a query, but use prepared statements and bind the user data to avoid the risk of SQL injection.
There are many ways to pass values from page to page but one is to use session variables:
//Include this at the top of your php scripts that use session variables
session_start();
$_SESSION['your_variable_name_here'] = value_you_want_to_store;
Then on the page you would like to access this use:
$someVariable = $_SESSION['your_variable_name_here'];
Change the SQL to return the show_id,
$sql = "SELECT show_id, show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
and use that as a parameter to the show_var_set() function.
<a href='#' onclick='show_var_set(".$row["show_id"].");'>".$row["show_title"]."</a>
The show_var_set() function can then use that parameter to get the details for that show from the database.
I'm learning PHP and SQL by running MAMP on my Mac, and accessing the database through phpMyAdmin.
I've made one PHP script to add a new user to a table, one for comparing inputted data with the table (login) and one to close an account. All of the scripts are very basic and the data isn't sanitized at all, as I'm just getting used to the basics of PHP.
I've noticed that after I run the script for account creation (inserting data), a few seconds after the script is run, a new row is added to the table with an id (which I've set to auto increment) but no other data.
I'm just wondering if the reason for this is something obvious in MySQL that I'm just missing.
The following is the account creation script:
<?php
//Get values from HTML form
$varUsername = $_POST['username'];
$varPassword = $_POST['password'];
$varPasswordHash = password_hash($varPassword, PASSWORD_DEFAULT);
//Establish connection to database
$server = "localhost";
$username = "root";
$password = "root";
$database = "members";
$connection = mysqli_connect($server, $username, $password, $database);
if(!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}
//Send data to database
$action = "INSERT INTO details (USERNAME, PASSWORD) VALUES ('$varUsername', '$varPassword')";
if(mysqli_query($connection, $action))
{
echo 'Account created.';
}
else
{
echo 'Account creation failed: ' . mysqli_error($connection);
}
mysqli_close($connection); //End connection to database
?>
and the HTML form to go with it:
<html>
<body>
<form action="sign_up.php" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
</body>
</html>
I'm making a guess right now...
I would add an extra if-statement to the script itself. Like this:
if (isset($_POST['submit-form'])) {
// All the above to insert the data into the script...
}
It would make sense if you visit the sign_up.php itself and notice there is a new entry made into your database.
You'll have to modify your HTML a little, to make the if-statement work.
Just add name='submit-form' to the submit button: <input type="submit" name="submit-form">
This will make the script more complete.
Also a little update on the matter as I just read that it adds an empty row after you submit an empty form.
You can check wether the fields are filled in with, guess what, another if-statement:
if (empty($_POST['username'])) {
echo 'Please enter your username...';
} else
if (...)
You do not verify if the POSTed values have anything in them, thus submitting an empty form results in an empty entry in the DB with just the ID.
I have troubles about php & mysql. I've to retrieve all records from DB1's table and then I have to insert them again to DB2's table.
<?php
require_once 'includes/config.php';
include 'includes/header.php';
if(isset($_POST['go'])){
$query = mysql_query("SELECT id,username,password FROM $db_database1.account")
or die(mysql_error());
echo "Record ".mysql_num_rows($query)." retrieve";
while($result_row = mysql_fetch_array($query, MYSQL_ASSOC)){
$account_ID = $result_row['id'];
$username = $result_row['username'];
$password = $result_row['password'];
$query = mysql_query("INSERT INTO $db_database2.account(uid,username,password) VALUES('$account_ID','$username','$password')")
or die(mysql_error());
$selectId = mysql_insert_id();
}
}
mysql_close($conn);
?>
<div class="wrapper">
<div class="content">
<form method="post" action="<?PHP $_SERVER['PHP_SELF'];?>">
<input type="submit" name="go" value="Go" />
</form>
</div>
<?php include 'includes/footer.php';?>
According to this code just one record was inserted. How can I insert all retrieved records?
To insert records into another table you need one single query, run from mysql console without PHP:
INSERT INTO db_database2.account SELECT id,username,password FROM db_database1.account
Notes on your code
you have to escape strings you are adding to the query
for some reason you are inserting into the same database
asking for the mysql_insert_id() makes no sense as you are apparently inserting a_i id already
there is no use for storing second mysql_query result into variable
yet this variable gets overwritten <- here is the reason your code runs once.
there is no use for echoing $_SERVER['PHP_SELF'] here. just leave form action blank.
yet you are actually leaving form action blank as you just forgot to echo this variable
I see no use for all the form and HTML here. Can't you just run this code without forms?
as it seems that whole mess is just to hash passwords, you need no extra tables then
just simple
UPDATE account SET password = md5(concat(id,username,password));
always have a database backup before such manipulations