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
Related
Before setting as duplicate, I've spent 4 hours on researching about my problem, but I had no luck.
I am trying to make a signup/login system for my website. The main point that doesn't seem to work is that when I am signing up on my website, the session doesn't seem to start. The reason that I can see it is because, on my navbar, I have set it to change from signup to log out. Here is the piece of code for that:
<ul>
<li class="list1">Home</li>
<li class="list2">About</li>
<li class="list3">Portfolio</li>
<li class="list4">Blog</li>
<li class="list4">Contact</li>
<?php
if (isset($_SESSION['id'])){
echo "<li><a href='#'>SIGN OUT</a></li>";
}
else{
echo "<li><a onclick='signup(event)' href='#'>SIGN UP</a></li>";
}
?>
</ul>
To make that I have created three files. One is the mane page, one is the signup file itself, code below:
<?php
session_start();
include "../dbh.php";
$first = $_POST["first"];
$last = $_POST["last"];
$uid = $_POST["uid"];
$email = $_POST["email"];
$pwd = $_POST["pwd"];
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$_SESSION['id'] = $row['id'];
header("Location: ../index.php");
exit();
and the last one is the file which connects PHP to the database code below:
$conn = mysqli_connect("XXX","XXX","XXX","XXX");
if (!$conn){
die("Connection failed: ".mysqli_connect_error());
}
I believe that the session doesn't start because the main page reloads after the user hits signup on the form, but I have started the session on all of my files (except the database connection file where it's not needed). I used session start on all of my page and I placed it on the beginning of all pages with opening and closing PHP tags.
Any suggestions? I appreciate your answers and comments!
Sorry for the bad English but it's not my first language.
This:
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
^^^^^^^^^^^^^^^^^^
$_SESSION['id'] = $row['id'];
Insert queries do NOT return a result set, and you can NOT fetch() from them. That means mysqli_fetch_assoc() is failing, and returning a boolean FALSE. You then use that boolean false as if it was an array, and are basically doing the equivalent of
$_SESSION['id'] = null;
Note this:
php > $foo = false;
php > $id = $foo['id'];
php > var_dump($id);
NULL
You want
$_SESSION['id'] = mysqli_insert_id($conn);
instead.
It is an error with you SQL query.
$sql = "INSERT INTO users (first,last,uid,email,pwd) VALUES ('$first','$last','$uid','$email','$pwd')";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
The first line of the code is an INSERT command. The second line executes this command by sending it to the server. If query is properly processed then MySQL server doesn't return you anything, so $result will equal to true. It wil not contain any data from the database. So you can't fetch it, what you try to do in the third line. Need to make a separate query for data.
I've been tossing and turning around why on earth this thing won't work.
The two strings won't combine and only the $title will be saved. How come? :(
even if the account is admin, it won't work. The value of account that will be saved is admin and yet the title wont concatenate. :(
See the code for yourself
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("fullcalendar", $con);
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$account= $_POST['account'];
$sumpay = 'USC' ;
if($account == "admin")
{
$ti= $title.$sumpay;
}
// insert the records
mysql_query("SELECT * FROM evenement");
mysql_query( "INSERT INTO evenement (id, title, start, end, account)
VALUES ('', '$ti', '$start', '$end' , '$account')");
?>
try using mysqli...
// first check the values posted using
print_r($_POST);
also make this change...
if($account == "admin")
$ti= $title.$sumpay;
else
$ti= $title;
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.
Ok I am making a registry for my website.
First page asks for some personal info
if($error==false) {
$query = pg_query("INSERT INTO chatterlogins(firstName, lastName, gender, password, ageMonth, ageDay, ageYear, email, createDate) VALUES('$firstNameSignup', '$lastNameSignup', '$genderSignup', md5('$passwordSignup'), $monthSignup, $daySignup, $yearSignup, '$emailSignup', now());");
$query = pg_query("INSERT INTO chatterprofileinfo(email, lastLogin) VALUES('$emailSignup', now());");
$userNameSet = $emailSignup;
$_SESSION['$userNameSet'] = $userNameSet;
header('Location: signup_step2.php'.$rdruri);
}
The first query works. The second query works but doesn't save the email...
the session doesn't work but the header works and sends me to the next page
I get no errors even if I comment out header
next page
#session_start();
$conn = pg_connect("host=localhost dbname=brittains_db user=brittains password=XXXX" );
$signinCheck = false;
$checkForm = "";
if(isset($_SESSION['$userName'])) {
$userName = $_SESSION['$userName'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
if(isset($_SESSION['$userNameSet'])) {
$userName = $_SESSION['$userNameSet'];
$signinCheck = true;
$query = pg_query("UPDATE chatterprofileinfo SET lastLogin='now()' WHERE email='$userName'");
}
This is the top starting the session depending on if your logged in or not.
then if I enter in the info here and put it through this
if($error==false) {
$query = pg_query("UPDATE chatterprofileinfo SET aboutSelf='$aboutSelf', hobbies='$hobbies', music='$music', tv='$tv', sports='$sports', lastLogin='now()' WHERE email='$userName'") or exit(pg_last_error());
//header('Location: signup_step3.php'.$rdruri);
}
nothing shows up for on my database from this.
I have no idea where I went wrong
the website is
http://opentech.durhamcollege.ca/~intn2201/brittains/chatter/
For starters, don't put things that aren't strings in single-quotes like that. 'now()' means a literal string "now()"
Also, if you're doing updates to your database you're better of using prepared statements to help prevent against sql injection. In your case, see http://www.php.net/manual/en/function.pg-prepare.php
This code was designed to upload files from a flash javascript uploader plugin.
It doesn't give me an error but sometimes it does not insert the mysql query.
P.s: every posted variable is cleaned up via javascript (just alphanumeric text)
<?php
include 'a/inc/db.php';
if (!empty($_FILES))
{
$tempFile = $_FILES['Filedata']['tmp_name'];
if (substr($_FILES['Filedata']['name'],-3)!='mp3')
{
echo 'ERROR: your file was not an mp3';
die();
}
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_POST['folder'] . '/';
$titlepost = $_POST['title'];
$tagspost = $_POST['tag'];
$artist= $_POST['artist'];
$i= $_POST['i'];
$targetFile = str_replace('//','/',$targetPath) .time().".mp3";
$targetFilea = $targetFile;
$targetFilea = substr($targetFilea , strrpos($targetFilea , 'music') -1);
move_uploaded_file($tempFile,$targetFile);
mysql_query('set names utf8');
$sql = mysql_query("INSERT INTO `Music` (`filename`, `title`, `tags`, `rating`, `click`, `rand`, `album`, `i`, `artist`)
VALUES ('".$targetFilea."', '".$titlepost."', '".$tagspost."', '0', '1', '".$ras."', '1', '".$i."', '".$artist."');")
or die(mysql_error());
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".$i."', 'upload', '".$titlepost."');")
or die(mysql_error());
$click = mysql_query("SELECT *
FROM `Music`
WHERE `filename`='".$targetFilea."' ;");
while($row = mysql_fetch_array( $click ))
{
$mid=$row['id'];
echo "<id>".$row['id']."</id>";
}
mysql_close($connection);
}
echo "1";
?>
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".$i."', upload', '".$titlepost."');")
there is a ' missing before upload
try this instead (also added mysql_real_escape_string for security):
$sqli = mysql_query("INSERT INTO `activity` (`from`, `what`, `text`)
VALUES ('".mysql_real_escape_string($i)."', 'upload', '".mysql_real_escape_string($titlepost)."');")
What really wrong is: your code is totally insecure. You sanitize POST-Data only using javascript and place it into your SQL query? Anybody can EASILY inject some custom SQL-Code and to really bad things to your database. Never ever rely on any HTTP-Data (be it GET, POST or anything else) to be secure.
I know you are new to PHP, so I honestly encourage you, for the sake of your customer, your project or anyone using your code, before you do anything else, sanitize your POST-Data with PHP before using it within SQL-Querys. Please.
There is even an article on Wikipedia on it, and it is a huge mistake newbies make with huge consequences which is quite easy to prevent.
http://en.wikipedia.org/wiki/SQL_injection
http://www.smashingmagazine.com/2009/03/24/10-useful-php-tips-revisited/ (Tip 1)
If the record is not getting inserted, this means most likely that there is some error. Possibly you have not set the proper error reporting that is why you don't see any error.
Put below two lines on top of your script so that all errors are shown.
ini_set('display_errors', true);
error_reporting(E_ALL);