I'm doing a transaction with PHP and MySQL. Using PHPMyAdmin I'm inserting queries into my University DB, where I'm supposed to use transactions in some tables. So far I've made this code for my Staff transactions, but my problem is how can I get the information inserted in addStaff.php so I can use it as a query on this code? right where it says //values();
<?php
function begin()
{
mysql_query("BEGIN");
}
function commit()
{
mysql_query("COMMIT");
}
function rollback()
{
mysql_query("ROLLBACK");
}
mysql_connect("localhost","username", "password") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query = "INSERT INTO Staff (id,name,position,phone,email,roomNumber,dnumber)"
//values();
begin(); // BEGIN
$result = mysql_query($query);
if(!$result)
{
rollback(); // ROLLBACK
echo "You rolled back";
exit;
}
else
{
commit(); // COMMIT
echo "Transaction was succesful";
}
?>
This is maybe what you're looking for:
$new_row = mysql_insert_id();
$query = mysql_query("SELECT * FROM `Staff` WHERE `id`=".$new_row);
$r = mysql_fetch_assoc($query);
echo $r['name'];
will echo the inserted rows name.
Edit: This is a very very basic version of how to do things, before moving anything to production you need to read up on SQL Injection, Prepared Statements/Escaping User Input, XSS Attacks and many more vital parts of SQL query security
If I understand you question correct, you need to know how to prompt for data, accept it, and insert it into the database:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... connect to the database ...
$sometext = $_POST['textfield']; // retrieve the value from the form
$qsometext = mysql_real_escape_string($sometext); // make it safe for the query
$sql = "INSERT INTO mytable (textfield) VALUES ($qsometext);" // build the sql query
$result = mysql_query($sql) or die(mysql_error()); // run the query
}
?>
<html>
<body>
<form method="POST">
<input type="text" name="textfield"><input type="submit">
</form>
</body>
</html>
That's a barebones version of how to show a form, then insert the user's data into a database, the simply re-displays the form for more data.
Related
Please help i commented off some stuff for testing purposes but nothing works
<?php
//retrieve the data sent in the POST request
$yourDateOrdered =$_POST["DateOrdered"];
$yourDueDate = $_POST["DueDate"];
if(isset($_POST["CompanyName"])){$yourCompanyName = $_POST["CompanyName"];}
//Validate the fields
if ($yourDateOrdered=="" || $yourDateOrdered==null){
$err= $err."Please enter the date the purchase order was made<br>";
}
if ($yourDueDate=="" || $yourDueDate==null){
$err= $err. "Please enter a date when the item is required<br>";
}
//if ($yourCompanyName=="" || $yourCompanyName==null){
//$err= $err."Please enter the customer name<br>";
//}
//Connect to the server and select database
include("dbConnection.php");
//define sql query to execute on the database
$Query1="INSERT INTO orders(CompanyName, DateOrdered, DueDate)
VALUES ('$yourCompanyName','$yourDateOrdered', '$yourDueDate')";
//execute query
//$result = mysql_query($Query1);
//echo("The following order has been added");
//result of the action stored in $Result
$Result = mysql_query($Query1);
if($Result){
echo 'Order entered';
echo Header ("Location:orderformitem.php");
}
//Close the connection
mysql_close($con);
//Check if query executed successfully and forward the user to an appropriate location
//if($queryResult){
//echo "Order save <br>";
//Header ("Location:../PHP/orderformitem.php");
//}
?>
You definietly need to learn how to debug. First, comment out the Header('Location ...'); row, to catch errors.
add error_reporting(E_ALL); and display_errors(1); at top of your file, to see any errors.
Let's var_dump($_POST) to see, is all the variables are correct.
Do a date validation, if you are want correct dates.
Dump your query, and try to run it in sql directly.
DO NOT use mysql functions because they are deprecated. Use mysqli or PDO instead.
Escape your data, to avoid sql injections!
I have a simple registration form that inserts data into MySQL table. I am checking for error as well but it results in SUCCESS echo.
On Stackoverflow, I looked for the question, but couldn't really find an answer pertaining to my situation. Please forgive me if it has been answered. If it has been answered already, please provide a link and I will apologize for wasting anybody's time. Thank you! Below is my code:
<?php
if($_GET["regname"] && $_GET["regpass1"] && $_GET["regpass2"])
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$servername="localhost";
$username="root";
$password='';
$conn= mysql_connect($servername,$username,$password)or die(mysql_error());
mysql_select_db("test")or die("cannot select DB");
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
if($sql)
{
echo "Success";
}
else
{
echo "Error";
}
print "<h1>you have registered sucessfully</h1>";
print "<a href='main_login.php'>go to login page</a>";
}
else print "passwords doesnt match";
}
else print"invaild data";
?>
You are checking if $sql exists. $sql is your actual query string. In this case, of course it will show it exists. Secondly, please do not use mysql_* for new code as it is deprecated. Instead use mysqli_* or PDO.
You actually haven't executed your query in your code. (Using deprecated mysql_* which is ill advised) the code as follows should execute the query:
$result = mysql_query($sql, $conn);
if($result == true)
echo 'Success';
else
echo 'Failure';
Instead of using the code above, I would strongly recommend updating your current code to use mysqli_* or PDO forms. You can read up more on this topic at the manpages linked previously.
Look at these lines:
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
if($sql)
{
echo "Success";
}
You have created a request in $sql variable but have not executed it. The variable itself is non-empty, non-false so it evaluates to TRUE in the if-condition.
You should do it like this:
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
$result = mysql_query($sql);
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
else
{
echo "Success";
}
Just to be on the safe side I'll note that using variables from $_GET request like this, unfiltered, is an inapprorpiate tactic as it will lead to SQL injections, but I suppose you simplified code sample for the sake of brevity.
Here is my code
<?php
require("db.php");
$datetoday = date("Y-m-d");
if (isset($_POST['submit']))
{
include 'db.php';
$loginid =$_REQUEST['loginid'];
$result = mysql_query("SELECT * FROM info WHERE id = '$loginid'");
$test = mysql_fetch_array($result);
$testid=$test['id'];
$fnameloginsuccess1=$test['firstname'];
$mnameloginsuccess1=$test['middlename'];
$lnameloginsuccess1=$test['lastname'];
$departmentloginsuccess1=$test['department'];
echo'<input type="text" name="fname" value="<?php echo $fnameloginsuccess1 ?>"/></td>';
if (!$loginid)
{header("location:../index.php"); }
$natureofleave =$_POST['group1'];
$datestart=$_POST['startofleave'];
$dateend=$_POST['endofleave'];
$reason=$_POST['reason'];
$status= 'pending';
mysql_query("INSERT INTO `request`(id,natureofleave,dateofleavestart,dateofleaveend,reasons,datesubmitted,department,status,firstname,middlename,lastname)
VALUES('$log','$natureofleave','$datestart','$dateend','$reason','$datetoday','$departmentloginsuccess1','$status','$fnameloginsuccess1','$mnameloginsuccess1','$$lnameloginsuccess1')");
}
my main problem is i can't put the value of $fnameloginsuccess1, $mnameloginsuccess1','$lnameloginsuccess1',$departmentloginsuccess1 on my database..
but i can "ECHO" them.. some values are working but the 4 values didn't work!!
i already tried fname = $fnameloginsuccess1'; sadly to say it didn't work..
HELP!!
<?php
require("db.php");
$datetoday = date("Y-m-d");
if (isset($_POST['submit']))
{
include 'db.php';
$loginid =$_REQUEST['loginid'];
if (!$loginid) {header("location:../index.php"); }
$result = mysql_query("SELECT * FROM info WHERE id = '$loginid'");
$test = mysql_fetch_array($result);
$testid=$test['id'];
$fnameloginsuccess1=$test['firstname'];
$mnameloginsuccess1=$test['middlename'];
$lnameloginsuccess1=$test['lastname'];
$departmentloginsuccess1=$test['department'];
echo'<input type="text" name="fname" value="'.$fnameloginsuccess1.'"/></td>';
$natureofleave =$_POST['group1'];
$datestart=$_POST['startofleave'];
$dateend=$_POST['endofleave'];
$reason=$_POST['reason'];
$status= 'pending';
mysql_query("INSERT INTO `request` (id, natureofleave, dateofleavestart, dateofleaveend, reasons, datesubmitted,department,status,firstname,middlename,lastname) VALUES('$log','$natureofleave','$datestart','$dateend','$reason','$datetoday','$departmentloginsuccess1','$status','$fnameloginsuccess1','$mnameloginsuccess1','$lnameloginsuccess1')");
}
?>
Consider to use PDO statements as mysql_query is deprecated since PHP 5.5.0 and will be removed in the future.
http://www.php.net/manual/en/function.mysql-query.php
PDO connection examples
http://www.code.rusben.com/php-pdo-connection-with-utf8-compatibility-select-insert-update-delete/
<?php
require_once("db.php");
$datetoday = date("Y-m-d");
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
$loginid = $_REQUEST['loginid'];
if (!$loginid)
{
header("Location: ../index.php");
exit;
}
$result = mysql_query("SELECT * FROM `info` WHERE `id` = '$loginid'");
$user = mysql_fetch_array($result);
$id = $user['id'];
$first = $user['firstname'];
$middle = $user['middlename'];
$last = $user['lastname'];
$dept = $user['department'];
$nature = $_POST['group1'];
$start = $_POST['startofleave'];
$end = $_POST['endofleave'];
$reason = $_POST['reason'];
$status = 'pending';
$sql = <<<SQL
INSERT INTO `request`
(`id`, `natureofleave`, `dateofleavestart`, `dateofleaveend`, `reasons`, `datesubmitted`, `department`, `status`, `firstname`, `middlename`, `lastname`)
VALUES
('$id', '$nature', '$start', '$end', '$reason', '$datetoday', '$department', '$status', '$first', '$middle', '$last');
SQL;
mysql_query($sql) or die ('There was an error processing your data.');
}
?>
A few points I feel the need to point out:
As you "require" the db.php, you should not need to "include" it.
When naming variables, it is best to keep them simple. Easier to debug and track down.
Exit the script after a header redirect. A delay in the header could allow further code to execute.
You can not use PHP tags inside of PHP tags - it just doesn't parse that way
I'd advise to write the SQL outside of the mysql_query() wrapper, since you can then echo out the SQL
Which can't be done if you write direct inside mysql_query()
log isn't defined, so it won't input. I'll assume that should be the users ID and edit to suit.
You had 2 dollar signs in the query (lnameloginsuccess1)
Anyway, if you run the above code and get "There was an error processing your data.", you can debug this pretty easily.
Change
mysql_query($sql) or die ('There was an error processing your data.');
to
mysql_query($sql) or die (mysql_error());
If the error it reports is vague, you tend to get better results running the query direct into the admin panel (PhpMyAdmin and the likes), so do;
On the line before the mysql query, simply add "echo $sql;" and run the page again. Copy the entire output of the query and run in your database admin panel.
If there is no error there, you need to be looking at connection issues - like errors in connection data
for admin panel i have made a table with delete, edit and add option with each row, every thing is working perfect except the execution of update query, uptil now have shown text to be edit in its form, and delivered the edit values to the next page which i have verified by usin echo(). My code is as following
update.php
<head>
<?php
// 1. Create a database connection
// 2. Select a database to use
include('connect.php');
?>
<?php
// 3. Perform database query
$id=$_SESSION['id'];
$author=$_GET['author'];
$quotation=$_GET['quote'];
//below code is to check
echo $id . "<br>". $author . "<br>". $quotation ."<br>";
//4. update query
$query = "UPDATE 'quotations' SET
'author' = '$author',
'quotation' = '$quotation',
WHERE 'id' = '$id'";
mysql_query($query);
// test to see if the update occurred
if (mysql_affected_rows() == 1) {
// Success!
echo "The page was successfully updated.";
} else {
echo "The page could not be updated.";
}
?>
<?php
// 5. Close connection
mysql_close($connection);
session_destroy();
//header("Location: Admin.php"); commented just to observe the output.
?>
</body>
</html>
by echo before query i`m getting my edit values which means there is no issue with the form, even db connected but no updates. Any suggession in this regard will be appreciated.
MySQL-escape your variables! Or better yet: use the mysqli/PDO prepared statements.
Additionally, your tablename is wrapped in single-quotes, and there is a stray comma before your WHERE clause. Use backquotes instead (or no quotes at all should be fine for that table name.)
$query = "UPDATE `quotations` SET
'author' = '$author',
'quotation' = '$quotation'
WHERE 'id' = '$id'";
MySQLi: http://php.net/manual/en/book.mysqli.php
MySQLi Prepared Statements: http://php.net/manual/en/mysqli.prepare.php
PDO: http://php.net/manual/en/book.pdo.php
PDO Prepared Statement method: http://php.net/manual/en/pdo.prepare.php
Is the id attribute in the database a numeric field? If so, you shouldn't be adding the single quotes in the UPDATE string.
$query = "UPDATE 'quotations' SET
'author' = '$author',
'quotation' = '$quotation',
WHERE 'id' = $id"
I am using the following code to pull all language variables and values form a MySQL database and populate a form for editing:
function language() {
$settings = array();
$sql = "SELECT * FROM `languages`";
$result = mysql_query($sql);
// Mysql_num_row is counting table row
while ($row = mysql_fetch_assoc($result)) {
?>
<div style="float:left;width:250px;padding-left:15px"><label><?php echo $row['id'];?></label></div><div style="float:left;margin-left:0px;"><input type="text" name="<?php echo $row['id'];?>" value="<?php echo $row['value'];?>" /></div>
<? php
}
}
I have a rudimentary function to save the changes made in the above form back to the database updating with any changes:
function save_language() {
$post = $_POST;
$out = array_shift($post);
// Mysql_num_row is counting table row
foreach($post as $key => $value) {
$sql = "UPDATE `languages` SET `value`='$value' WHERE `id`='$key'";
$result = mysql_query($sql);
}
if ($result) {
echo "Language Settings Updated";
}
}
This method works but it is very slow. I am new to coding and I am sure I am overlooking something simple that would speed up the saving process.
Your query actually shouldn't be working because the connection is out of scope of the function. The correct way to pass the connection would be through the function:
function language( $conn ) {
...
}
You should immediately stop using your code due to injection vulnerabilities as well as the deprecation of mysql_ functions. Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
Depending on how many records you are updating and how many connections you are making, it may slow down your script.
If you wish to INSERT records, you need to be using prepared statements.
Also, I don't understand the commnet // Mysql_num_row is counting table row in your save_language function as you are not using the number of rows from the result anywhere.