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;
Related
I have created a certain form for my website that includes a Textarea with formatted text option so that the user can bold, underline, italics but also insert bulleted points and ordered list or even changing the font type and size.
The problem is when the user opts to insert ordered list then click the submit button the information is stored in the server as [ol] enclosed in square brackets which is not appropriate especially when I want to display the information on the website so I was thinking maybe if the information could be stored as enclosed in HTML tags it will make it easier for displaying the information on the website whenever such information is called.
My question is how can I store the information in tags(<>) instead of the ones enclosed in square brackets[]?
here is the code that gets the data from the form I tried to use the htmlspecialchars function but it didn't work.
<?php
session_start();
include 'connect.php';
$servername = $_SERVER['PHP_SELF'];
$username = 'root';
$password = '';
$dbname = 'members';
$tablename = 'jobs';
if (isset($_SESSION['username'])){ $sessionuser =
$_SESSION['username'];}
else if (isset($_SESSION['company'])){$sessionuser =
$_SESSION['company'];}
if(isset($_POST['company_name'])){
$company_name = $_POST['company_name'];
}
else if(isset($_SESSION['company'])){ $company_name = $_POST['company'];
}
$company_website = $_POST['company_website'];
$job_requirement = htmlspecialchars($_POST['job_requirement']);
$location = $_POST['location'];
$job_title = $_POST['job_title'];
$application_email_url = $_POST['application_email_url'];
$application_deadline = $_POST['application_deadline'];
$category = $_POST['category'];
$job_type = $_POST['job_type'];
if($_SERVER['REQUEST_METHOD']){
$sql = "INSERT INTO $tablename (`Company_name`, `Company_website`,
`Job_requirement`, `Location`, `Job_title`, `Application_deadline`,
`Category`, `Job_type`, `username`,`application_email_url`)
VALUE('$company_name', '$company_website', '$job_requirement',
'$location', '$job_title', '$application_deadline', '$category',
'$job_type', '$sessionuser', '$application_email_url')";}
if($conn->query($sql)===TRUE){ print "your job has been posted";}
else{echo "error" .$conn->error;}
?>
Try using htmlspecialchars() on the string to put into the DB, and then, when pulling it back out, use htmlspecialchars_decode(). Might make a difference.
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 have this SQL statement that i'm trying to get to save new students to a table of students, however it simply isn't doing it, I don't get any error messages when I run error reporting and I ran the Query in sqlbuddy with values swapped in and it worked fine. Any ideas on what im doing wrong will be appreciated.
Heres the code:
<?php
session_start();
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
$default = 'default';
$ClassID = $_GET['ID'];
$Surname = $_POST['Surname'];
$Firstname = $_POST['Firstname'];
$Firstletter = $Firstname[0];
$Username = $Firstletter + $Surname;
$sql_link = mysqli_connect('localhost', 'root', 'password', 'GameData');
$counter = mysqli_query($sql_link,"SELECT * FROM IDCounter");
$counter = mysqli_fetch_array($counter);
mysqli_query($sql_link,"INSERT INTO tblStudents(StudentID, StudentFirstName, StudentSurname, ClassID, UserName, Password, CharacterSelect)
VALUES ('$counter[Counter]', '$_POST[Firstname]', '$_POST[Surname]', '$ClassID', '$Username', '$default', 1)");
mysqli_close($sql_link);
header ("Location: TeacherSide.php");
?>
The POST values come from the form that directs to this page
I just worked out the issue I was having and I regret to inform you it was a rather stupid one, I was not updating my counter, So every time I tried to add a new student it would try with the same StudentID, and thus would fail, an easy fix
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
I have this code to insert into a table. My issue with INSERT INTO categories is that its never inserting data into the table and there is no error. I am using almost the same query in code with a different table and there it's working. Any clue?
<?php
$action = $_GET['action'] ;
if ($action=='question')
question();
elseif ($action=='categories')
categories();
function question() {
if ((isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true))
{
$include("db.php");
$category = $_POST['category'] ;
$subcategory = $_POST['subCategory'] ;
$question = $_POST['question'] ;
$answer = $_POST['answer'] ;
$query = "INSERT INTO faq (category,subcategory,question,answer)
VALUES('.$category.','.$subcategory.','.$question.','.$answer')";
$success = mysql_query($query);
if ($success)
{
echo '<a href="admin.php" >done >';
}
else
{
echo mysql_error();
}
}
}
function categories(){
if ( ! (isset($_SESSION['loggedin']) && ! $_SESSION['loggedin'] == true))
{
include("db.php");
$category = $_POST['category'] ;
$subcategory = $_POST['subCategory'] ;
$query = "INSERT INTO categories (category,subcategory)
VALUES( '$category' , '$subcategory')";
$success = mysql_query($query);
if ($success)
{
echo '<a href="admin.php" >done>';
}
else
{
echo mysql_error();
}
}
}
?>
A few issues:
If you are combining variables into a string, you can use the "." character to join them, or you can include variables within the string, so long as the string is wrapped in double quotation marks. In your code, you were doing both at once.
You were not santising your database input.
Your logic checks for the "categories" function were incorrect.
Your hyperlink tags were missing the closing tags.
See the amended code below.
<?php
$action = $_GET['action'];
if( $action=='question' )
question();
elseif( $action=='categories' )
categories();
function question(){
if( isset( $_SESSION['loggedin'] ) && $_SESSION['loggedin'] == true ){
include( 'db.php' );
$category = mysql_real_escape_string( $_POST['category'] );
$subcategory = mysql_real_escape_string( $_POST['subCategory'] );
$question = mysql_real_escape_string( $_POST['question'] );
$answer = mysql_real_escape_string( $_POST['answer'] );
$query = "INSERT INTO faq ( category , subcategory , question , answer ) VALUES( '{$category}' , '{$subcategory}' , '{$question}' , '{$answer}' )";
echo "SQL Query to execute: $query"; # Debug Message
$success = mysql_query( $query );
if ( $success ){
echo 'done';
}else{
echo mysql_error();
}
}
}
function categories(){
if( !( isset( $_SESSION['loggedin'] ) || $_SESSION['loggedin']==true ) ){
include( 'db.php' );
$category = mysql_real_escape_string( $_POST['category'] );
$subcategory = mysql_real_escape_string( $_POST['subCategory'] );
$query = "INSERT INTO categories ( category , subcategory ) VALUES ( '{$category}' , '{$subcategory}' )";
echo "SQL Query to execute: $query"; # Debug Message
$success = mysql_query( $query );
if( $success ){
echo 'done';
}else{
echo mysql_error();
}
}
}
First off, to help debugging, I'd put these two lines at the top of your scripts to show all the errors produced. Don't put these in a production environment, however.
error_reporting(E_ALL);
ini_set('display_errors', '1');
Change
$query = "INSERT INTO faq (category,subcategory,question,answer) VALUES('.$category.','.$subcategory.','.$question.','.$answer')";
To this:
$query = "INSERT INTO faq (category,subcategory,question,answer) VALUES('".$category."','".$subcategory."','".$question."','".$answer."')";
You have missed out a . (dot) after $answer; it was a syntax error, not a query error.
To make things a bit simpler, you can actually omit the dots completely:
$query = "INSERT INTO faq (category,subcategory,question,answer) VALUES('$category','$subcategory','$question','$answer')";
Do be aware of SQL injection attacks; use mysql_real_escape_string() to make your query safe(er)
Another issue might be your include file. Try changing
include("db.php");
To
require("db.php");
This will fail if the include file can't be found. In this case, go fix!
I had the same problem, used or die(mysql_error()); and realized I wasn't doing addslashes($string) on one of my variables. It had characters I needed to escape.
I had the same mysterious situation. And worse, on a remote, identical, database the same code was working. The solution was to define a default value (any value) to all the database fields... Hope this helps.
i have been stuck in this problem for a long time the only solution i found is
use mysqli instead of mysql because in newer versions of php these mysql has been deprecated for example
use the following methods
and make sure keep the order correct dirst the variable e.g '$conn' and then database name in the method 'mysqli_select_db($conne,'checksum');'.
similarly in 'mysqli_query($conne,$enter_command);' first variable and then the variable for query.
$conn=mysqli_connect($mysql_host,$mysql_user,$mysql_password);
mysqli_select_db($conne,'checksum'); // checksum is database name
mysqli_query($conne,$enter_command);
mysqli_close($conne);
also make sure to give spaces when entering database table columns
$enter_command = "INSERT INTO dbase (name , lastname , password) VALUES ('".$name."','".$lastname."','".$password."')";
you can also use this syntax
$enter_command = "INSERT INTO dbase (name , lastname , password) VALUES ('{$name}','{$lastname}','{$password}')";
try avoiding sql injection
$gender = mysql_real_escape_string($_POST['gender']);
hope this will work
Your code is working just fine, The issue here is the database auto increment was not set. This can happen When auto increment is not set. you will not be able to insert additional records beyond one no matter how many times you run your script. If you are having this kind of issue, check to make sure auto increment is enabled.
This is not really an error but the developer of mysql or php should give a warning when the user forgets to enable auto increment so the user has the option to fix it or ignore it.