SQL statement in php will not insert onto database - php

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

Related

PHP not showing any error, the latter 2 else if statements are working well, but not the first one

<?php
$db = mysqli_connect('localhost', 'username', 'password', 'database');
$username = "";
$password = "";
$regcode = "";
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$regcode = $_POST['regcode'];
$sql_R = "SELECT * FROM regcode WHERE regcode='$regcode'";
$sql_R2 = "SELECT * FROM staff WHERE regcode='$regcode'";
$res_R2 = mysqli_query($db, $sql_R2);
$res_R = mysqli_query($db, $sql_R);
if ((mysqli_num_rows($res_R) > 0) && (mysqli_num_rows($res_R2) < 1)){
$query = "INSERT INTO staff (username, password, regcode)
VALUES ('.$username.', '.$password.', '".$regcode."')";
$results = mysqli_query($db, $query);
echo file_get_contents("register.html");
exit();
}else if(mysqli_num_rows($res_R2) > 0){
$regcode_error = "Reg.Code already used by someone, please inform administrator for further information.";
}else{
$regcode_error = "Reg.Code doesn't exists, please inform Administrator for further information.";
}
}
?>
Here's what happened: I'm trying to let my system recognize a code called 'regcode' from the database so when it's verified users will able to register their account, user won't be able to register their account IF the regcode is in use in the staff database or when the regcode isn't exist in the regcode database the problem is:
- My database didn't add the new info after it's verified.
- I've tried the other way such as testing the regcode invalid or being in use, and it works well by displaying the error message.
I'm trying to figure this out like hours, and I still can't get it. I'm new to php btw, thanks for the advice.
This line is incorrect
VALUES ('.$username.', '.$password.', '".$regcode."')";
it should be
VALUES ('$username', '$password', '$regcode'";
You were concatenating, incorrectly and where you didnt need to, remember double quoted strings will automatically expand $variables
NOTE: Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
This would have been easier for you to debug yourself if you included some error checking code. Add
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
to the top of your script. This will force any mysqli_ errors to
generate an Exception that you can see on the browser and other errors will also be visible on your browser.

apache2 and php - please advise

OK, I originally posted this a question about php, but have since realized it could be a server configuration problem, which I know little about. I left the php script in case, and am hoping someone might have some pointers on this - I already checked permissions (755).
"NetworkError: 500 Internal Server Error - http://localhost/register.php?name=uname&password=upassword"
I was hoping someone here would be able to catch my error - sorry if this is obvious I've been learning as I go.
<?php
define('USER', 'root');
define('PASS', 'password');
$dbh = new PDO('mysql:host=localhost;dbname=users', USER, PASS);
$uname = $_POST['uname'];
$upassword = password_hash($_POST['upassword'], PASSWORD_DEFAULT);
$query = 'INSERT INTO `users` (`name`, `password`) VALUES (?,?)';
$query->bind_param($uname, $upassword);
$queryResults = $dbh->prepare($query);
$queryResults->execute();
$queryResults = null;
$dbh = null; // close the connection
?>
This keeps giving me a 500 internal server error indicating the php script, (in firebug for firefox), and I can't really figure out where I'm going wrong. I can also post ajax if needed.
You are using a Query String http://localhost/register.php?name=uname&password=upassword". Its purely a GET Method.
Your have to check whether the GET Method is exist then you need to access the GET Method Data.
$uname = "";
if(isset($_GET['uname'])) {
$uname = $_GET['uname'];
}
$upassword = "";
if(isset($_GET['password'])) {
$upassword = $_GET['password'];
}
if(($uname != "") && ($upassword != "")) {
$upassword = password_hash($upassword, PASSWORD_DEFAULT)
$query = sprintf("INSERT INTO `users` (`name`, `password`) VALUES (%s, %s)", $uname, $upassword);
----- Statements ------
}
I don't know why it's throwing 500 error, but you clearly have error in code.
Your $query variable is string and it does not have $query->bind_param() method. I assume you are trying to do this (bind_param is MySqli while bindParam is PDO):
$dbh->prepare($query);
$sth->bindParam($uname, $upassword);
Also since you are passing variables via URL, than you must use $_GET instead of $_POST. Just make sure you first check if these parameters exists in $_GET and only than use them:
if (!empty($_GET['name'])) {
$uname = $_GET['name'];
}
NOTE ?name=uname&password=upassword means variable names are name and password. It's values are $_GET['name'] = 'uname' / $_GET['password'] = 'upassword'.
Never pass username and password using $_GET as it's insecure. Better use some secure file to save them.

How to insert a new record to the table created in mysql

I created a table in mysql as'cus_info'. It has columns as 'iD' 'NAME' 'PASSWORD' 'eMAIL'. iD column is auto increment. I want to insert a new row to this table when a new customer registered. For that I wrote the following code in PHP
<?php
error_reporting(0);
require "init.php";
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."');";
if(!mysql_query($con, $sql)){
echo '{"message":"Unable to save the data to the database."}';
}
?>
but always I get the message as "unable to save data to the database"
Could you please tell me where I have gone wrong?
Thanks in advanced.
Could you please tell me where I have gone wrong?
In more than one place.
To most directly answer your question, you can use mysql_error() to print the error you're getting from mysql. To even more directly answer it, you have swapped the order of the parameters and you don't need the semicolon to be included in the query. (See example code here.)
You shouldn't be using PHP's "mysql_*" functions, which were deprecated in PHP5.5 and even removed in PHP7. You also should not be passing user input from a form directly into a MySQL database without any cleaning.
First show your $con and then put error_reporting(1) to check if other error occurs.
And finnaly copy and replace in your code.
$sql = "INSERT INTO `cus_info` (`name`, `password`, `email`) VALUES ('".$name."', '".$password."', '".$email."')";
Try This
<?php
error_reporting(0);
require "init.php";
if(isset($_REQUEST["save"]))
{
$name = $_POST["name"];
$password = $_POST["password"];
$email = $_POST["email"];
$sql = mysql_query("INSERT INTO `cus_info` (`name`,`password`,`email`) VALUES ('$name','$password','$email')");
$values=mysql_insert_id();
if($values!='')
{
echo '{"message":"Successfully save the data to the database."}';
}
else
{
echo '{"message":"Unable to save the data to the database."}';
}
}
?>

Having trouble with concatenating two strings

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;

how to call the value in mysql then turn into a variable

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

Categories