PHP and MySQL query based on user input not working - php

I am creating a users database where there are 4 fields: ID, username, password, and occupation. This is a test database. I tried querying the db table and it worked but i have a lot of trouble having a user input and a MySQL query based off of it. I run an Apache server in Linux (Debian, Ubuntu).
I have 2 pages. The first one is a bare-bone test index page. this is where there are textboxes for people to input easy info to register their info in the db. Here is the code for it:
<html>
<form action="reg.php" method="POST">
Username:
<input type="text" name="u">Password:
<input type="password" name="p">Occupation:
<input type="text" name="o">
<input type="submit" value="register">
</form>
</html>
After the submit button is clicked. It goes to the reg.php file. This is where it gets complicated. The page goes blank!!! Nothing is displayed or inputted in the db. Normal queries work well, but when user interaction is added, something is wrong. Here is the code for reg.php:
<?php
$un = $_POST["u"]
$pk = $_POST["p"]
$ok = $_POST["o"]
$u = mysql_real_escape_string($un);
$p = mysql_real_escape_string($pk);
$o = mysql_real_escape_string($ok);
$link = mysql_connect('localhost', 'root', 'randompassword');
if (!$link){
die(' Oops. We Have A Problem Here: ' . mysql_error());
}
if ($link){
echo 'connected succesfully';
}
mysql_select_db("forum") or die(' Oops. We Have A Problem Here: ' . mysql_error());
$data = mysql_query("INSERT INTO users (username, password, occupation) VALUES ('{$u}', '{$p}', '{$o}')");
?>
Can anyone hep me to correct this code to make this work?
Thank you so much for your time. Much appreciated.
EDIT:
I noticed that i did not add semicolons in the first 3 lines. after doing so i got this error: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{'', '', '')' at line 1." Can someone explain why?
EDIT: the website is just on my local machine...
on an apache server on linux

You are missing semi-colons in the first three lines.
$un = $_POST["u"];
$pk = $_POST["p"];
$ok = $_POST["o"];

mysql_real_escape_string() requires a db connection.
Try this ....
<?php
$un = $_POST["u"];
$pk = $_POST["p"];
$ok = $_POST["o"];
$link = mysql_connect('localhost', 'root', 'randompassword');
if (!$link){
die(' Oops. We Have A Problem Here: ' . mysql_error());
}
if ($link){
echo 'connected succesfully';
}
mysql_select_db("forum") or die(' Oops. We Have A Problem Here: ' . mysql_error());
$u = mysql_real_escape_string($un);
$p = mysql_real_escape_string($pk);
$o = mysql_real_escape_string($ok);
$sql = "INSERT INTO users (username, password, occupation) VALUES ('$u', '$p', '$o')";
$ins_sql = mysql_query($sql);
IF($ins_sql) {
echo 'Inserted new record.';
}ELSE{
echo 'Insert Failed.';
}
?>

Try adding this to the top of your script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
This way you will see all errors that you made syntactically or even within your SQL.

Related

PHP sql insert code is returning false even when sql command if correct and database is too

Once again I come back to all of you with another question.
I have tried everything in my mind as well as most of the recommendations I have found on the web and here in Stackoverflow but nothing seems to fix this issue for me.
For some reason the sql command in my code is returning false even though it should not.
Here is my php file called (dbRKS-DBTest.php)
<?php
//Gets server connection credentials stored in serConCred.php
//require_once('/../prctrc/servConCred2.php');
require_once('C:\wamp64.2\www\servConCred2.php');
//SQL code for connection w/ error control
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(!$con){
die('Could not connect: ' . mysqli_connect_error());
}
//Selection of the databse w/ error control
$db_selected = mysqli_select_db($con, DB_NAME);
if(!$db_selected){
die('Can not use ' . DB_NAME . ': ' . mysqli_error($con));
}
//VARIABLES & CONSTANTS
//Principal Investigator Information
$PI_Selected = '6';
//Regulatory Knowledge and Support Core Requests variables
$RKS_REQ_1_Develop = '1';
//This sets a starting point in the rollback process in case of errors along the code
$success = true; //Flag to determine success of transaction
//start transaction
$command = "SET AUTOCOMMIT = 0";
$result = mysqli_query($con, $command);
$command = "BEGIN";
$result = mysqli_query($con, $command);
//Delete this portion of code afyer testing is finished
//Core Requests saved to database
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop')";
//*************TEsts code for "SCOPE_IDENTITY()" -> insert_id() for mysql
$sqlInsertId = mysqli_insert_id($con); //This value is supposed to be 0 since no queries have been executed.
echo "<br>MYSQLi_INSERT_ID() value before query should be 0 and it is:= " . $sqlInsertId;
//Checks for errors in the db connection.
$result = mysqli_query($con, $sql); //Executes query.
if($result == false){ //Checks to see for errors in previews query ($sql)
//die ('<br>Error in query to Main Form: Research Proposal Grant Preparation: ' . mysqli_error($con));
echo "<br>Result for the sql run returned FALSE. Check for error in sql code execution.";
echo "<br>Error given by php is: " . mysqli_error($con);
$success = false; //Chances success to false is it encounted an error in order to rollback transaction to database
}
else{
//*************TEsts code for "SCOPE_IDENTITY()" -> insert_id() for mysql
$sqlInsertId = mysqli_insert_id($con); //Saves the last id entered. This would be for the main table
echo "<br>MYSQLi_INSERT_ID() value after Main form query= " . $sqlInsertId; //Displays id last stored. This is the main forms id
$MAIN_ID = mysqli_insert_id($con); //Sets last entered id in the MAIN Form db to variable
}
//Checks for errors or craches inside the code
// If found, execute rollback
if($success){
$command = "COMMIT";
$result = mysqli_query($con, $command);
echo "<br>Tables have been saved witn 0 errors.";
}
else{
$command = "ROLLBACK";
$result = mysqli_query($con, $command);
echo "<br>Error! Databases could not be saved. <br>
We apologize for any inconvenience this may cause. <br>
Please contact a system administrator at PRCTRC.";
}
$command = "SET AUTOCOMMIT = 1"; //return to autocommit
$result = mysqli_query($con, $command);
//Displays message
//echo '<br>Connection Successfully. ';
//echo '<br>Database have been saved';
//Close the sql connection to dababase
mysqli_close($con);
?>
Here is my php frontend html code named (RPGPHomeQueryTest.php)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<form id="testQuery" name="testQuery" method="post" action="../dbRKS-DBTest.php" enctype = "multipart/form-data">
<input type="submit" value="Submit query"/>
</form>
</html>
And here is how my database looks (rpgp_form_table_3):
So, when I open my html code, All I will see is a button since its all the code there is there. Once you press the button, the form should submit and execute the php code called (dbRKS-DBTest.php). This should take the predetermine values I already declared and saved them to the database called (rpgp_form_table_3). This database is set to InnoDB format.
Now, the output I should be getting is a message saying "Tables have been saved witn 0 errors." but the problem is that the message I am getting is this one bolow:
I honestly don't know why. I am posting this message to find guidance to this issue. I am still learning by myself and its been very did-heartedly to not find a solution this fixing this.
As always, I thank you for your patient and guidance! Let me know what other details I can provide.
Here is the SQL code you run:
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop')";
You are inserting data into rpgp_form_table_3. From the screenshot, we can see that table has several (7) fields yet you are only inserting 2 fields. The question then is: do you need to specify a value for all fields?
The error you are getting states
Error given by php is: Field 'idCollaRecord_1' doesn't have a default value Error! Databases could not be saved.
It's clear that you have to insert the row by specifying a value for each column, not just the two columns you are interested in.
Try
$sql = "INSERT INTO rpgp_form_table_3 (idPl, RKS_REQ_1_Develop, idCollaRecord_1, idCollaRecord_2, idCollaRecord_3, idCollaRecord_4)
VALUES ('$PI_Selected', '$RKS_REQ_1_Develop',0,0,0,0)";
Try this insert code. If the PI_Selected is NUMERIC use the First one. If it is string use the second one
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop) VALUES (" .
$PI_Selected . ",'" . $RKS_REQ_1_Develop . "')";
$sql = "INSERT INTO rpgp_form_table_3 (idPI, RKS_REQ_1_Develop) VALUES ('" .
$PI_Selected . "','" . $RKS_REQ_1_Develop . "')";

How to insert long Strings into mySQL database using PHP?

I'm using a simple html-form and PHP to insert Strings into mySQL Database, which works fine for short strings, not for long ones indeed.
Using the phpmyadmin I'm able to insert Strings of all lengths, it's only doesn't work with the html file and PHP.
Will appreciate every kind of help, would love to learn more about this topic...
Thank you all a lot in advance and sorry if the question is to simple...
There are two very similar questions, I found so far... unfortunately they couldn't help:
INSERTing very long string in an SQL query - ERROR
How to insert long text in Mysql database ("Text" Datatype) using PHP
Here you can find my html-form:
<html>
<body>
<form name="input" action = "uploadDataANDGetID.php" method="post">
What is your Name? <input type="text" name="Name"><br>
Special about you? <input type="text" name="ThatsMe"><br>
<input type ="submit" value="Und ab die Post!">
</form>
</body>
</html>
and here is the PHP-Script named uploadDataANDGetID.php :
<?php
$name = $_POST["Name"];
$text = $_POST["ThatsMe"];
$con = mysql_connect("localhost", "username", "password") or die("No connection established.");
mysql_select_db("db_name") or die("Database wasn't found");
$q_post = mysql_query("INSERT INTO profiles VALUES (null, '{$name}' ,'{$text}')");
$q_getID =mysql_query("SELECT ID FROM profiles WHERE Name = '{$name}' AND ThatsMe = '{$text}'");
if(!$q_post) // if INSERT wasn't successful...
{
print('[{"ID": "-3"}]');
print("uploadDataAndGetID: Insert wasn't successful...");
print("about ME: ".$text);
}
else // insertion succeeded
{
while ($e=mysql_fetch_assoc($q_getID))
$output[]=$e;
//checking whether SELECTion succeeded too...
$num_results = mysql_num_rows($q_getID);
if($num_results < 1)
{
// no such profile available
print('[{"ID": "-1"}]');
}
else
{
print(json_encode($output));
}
}
mysql_close();
?>
Thank you guys!
Use the newer way to connect to MySQL and use prepared statements http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
you MUST escape your strings, with mysql_real_escape_string, like this:
$name = mysql_real_escape_string($_POST['Name']);
$text = mysql_real_escape_string($_POST["ThatsMe"]);
$q_post = mysql_query('INSERT INTO profiles VALUES (null, "' . $name . '" ,"' . $text . '")');
also read about SQL injection

PHP and MySQL posting system

Okay, Here's my problem. I am trying to make a posting script for my website. However this script is not working; the script is below:
<?php
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit'])) {
// Grab the profile data from the POST
$post1 = mysqli_real_escape_string($dbc, trim($_POST['post1']));
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
$error = false;
mysqli_close($dbc);
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<legend>Posting</legend>
<label for="post">POST:</label>
<textarea rows="4" name="post1" id="post" cols="50">Write your post here...</textarea><br />
<input type="submit" value="submit" name="submit" />
</form>
</div>
<?php
include ("include/footer.html");
?>
</body>
</html>
Nothing shows up in the database when I submit the form. Help would be amazing. Thanks.
You haven't executed the query. All you've done is opened a connection, defined the query string and closed the connection.
Add:
if(msyqli_query($dbc, $query)) {
// Successful execution of insert query
} else {
// Log error: mysqli_error($dbc)
}
after this line:
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
Update:
Started editing but had to leave... As other answerers have pointed you need to either quote the post column with a backick or remove the single quote that you currently have altogether. The only case where you need to use backticks to escape identifiers that are one of the MySQL Reserved Words.
So the working version of your query would be:
$query = "INSERT INTO ccp2_posts (post) VALUES ('$post1')";
You may have other problems, but your SQL is bad. You can't use single quotes around 'post'. You want backticks or nothing:
INSERT INTO ccp2_posts(post) VALUES ('$post1')
You missed
mysqli_query($dbc,$query);
In your code,
$query = "INSERT INTO ccp2_posts ('post') VALUES ('$post1')";
mysqli_query($dbc,$query);
Your query is not quite right:
$query = "INSERT INTO `ccp2_posts` (`post`) VALUES ('$post1')";
Note that those are backticks `, not single-quotes. This is very important! Backticks are used to name databases, tables and column names, and in particular it means you don't have to remember the extensive list of every single reserved word. You could call your column `12345 once I caught a fish alive!` if you want to!
Anyway, more importantly, you aren't actually running your query!
mysqli_query($dbc,$query);
You are not submiting to the database using, for example, the mysql_query() function.

Cannot INSERT data into mysql using php

I have been trying for two days now to figure this one out. I copied verbatim from a tutorial and I still cant insert data into a table. here is my code with form
<font face="Verdana" size="2">
<form method="post" action="Manage_cust.php" >
Customer Name
<font face="Verdana">
<input type="text" name="Company" size="50"></font>
<br>
Customer Type
<font face="Verdana">
<select name="custType" size="1">
<option>Non-Contract</option>
<option>Contract</option>
</select></font>
<br>
Contract Hours
<font face="Verdana">
<input type="text" name="contractHours" value="0"></font>
<br>
<font face="Verdana">
<input type="submit" name="dothis" value="Add Customer"></font>
</form>
</font>
<font face="Verdana" size="2">
<?php
if (isset($_POST['dothis'])) {
$con = mysql_connect ("localhost","root","password");
if (!$con){
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES
('$_POST[Company]','$_POST[custType]','$_POST[contractHours]')";
mysql_query($sql, $con);
print_r($sql);
mysql_close($con);
}
?>
This is my PHPmyadmin server info:
Server: 127.0.0.1 via TCP/IP
Software: MySQL
Software version: 5.5.27 - MySQL Community Server (GPL)
Protocol version: 10
User: root#localhost
Server charset: UTF-8 Unicode (utf8)
PLEASE tell me why this wont work. when I run the site it puts the info in and it disappears when I push the submit button, but it does not go into the table. There are no error messages that show up. HELP
I have improved a little bit in your SQL statement, stored it in an array and this is to make sure your post data are really set, else it will throw a null value. Please always sanitize your input.
in your Manage_cust.php:
<?php
if (isset($_POST['dothis']))
{
$con = mysql_connect ("localhost","root","password");
if (!$con)
{
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$company = isset($_POST['Company'])?$_POST['Company']:NULL;
$custype = isset($_POST['custType'])?$_POST['custType']:NULL;
$hours = isset($_POST['contractHours'])?$_POST['contractHours']:NULL;
$sql = "INSERT INTO cust_profile(Customer_Name,
Customer_Type,
Contract_Hours)
VALUES('$company',
'$custype',
'$hours')
";
mysql_query($sql, $con);
mysql_close($con);
}
?>
First of all, don't use font tags...ever
Secondly, because of this line:
if (isset($_POST['dothis'])) {
It looks like your HTML and PHP are combined into one script? In which case, you'll need to change the action on the form to something like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Plus, you can kill a bad connection in one line:
$con = mysql_connect("localhost","root","password") or die("I died, sorry." . mysql_error() );
Check your posts with isset() and then assign values to variables.
var $company;
if(isset($_POST['Company']) {
$company = $_POST['Company'];
} else {
$company = null;
}
//so on and so forth for the other fields
Or use ternary operators
Also, using the original mysql PHP API is usually a bad choice. It's even mentioned in the PHP manual for the API
Always better to go with mysqli or PDO so let's convert that:
//your connection
$conn = mysqli_connect("localhost","username","password","averyit_net");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours)
VALUES ($company,$custType,$contractHours)";
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Assuming you set these
$stmt = mysqli_prepare($conn, $sql);
$stmt->execute();
$stmt->close();
Someone tell me if this is wrong, so I can correct it. I haven't used mysqli in a while.
Change the $sql to this:
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES ('".$_POST[Company]."','".$_POST[custType]."','".$_POST[contractHours]."')

How do I complete this login script?

I've almost completed my login script, but I don't know how to check if the username & password is correct.
Here's my script files.
index.php:
<html>
<body>
<form action="action1.php" method="post">
Username: <input type="text" name="uname">
Password: <input type="password" name="pword">
<input type="submit">
</form>
</body>
</html>
The index.php file is just the page that I use to collect the info from my users for registration.
action1.php:
<?php
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die ('Could not connect: ' . mysql_error());
}
mysql_select_db("user1", $con);
$sql="INSERT INTO useri1 (uname, pword)
VALUES
('$_POST[uname]','$_POST[pword]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The action1.php file is just the page that registers the users into the database.
login.php:
<html>
<body>
<form action="checklogin.php" method="post">
Username: <input type="text" name="uname1">
Password: <input type="password" name="pword1">
<input type="submit">
</form>
</body>
</html>
The login.php file is just the page I use for the users to type their login info in.
Now this is my problem, I have no idea of how to check the users login info so they can proceed to the members only area. I'm a newbie & any help is GREATLY appreciated.
Thanks,
--Devin
Firstly you want to use mysqli instead of mysql, because mysql is outdated and no longer actively developed. Secondly you want to start escaping your database queries to stop sql injection. In the code below, I used a session to keep track of the user. You can learn more about sessions here.
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'user1');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$userName = $mysqli->real_escape_string($_POST['uname1']);
/* query database */
$result = $mysqli->query("SELECT `pword` FROM `user1` WHERE `uname` = '".$userName."'");
if ($result->num_rows == 1) {
while ($col = $result->fetch_array(MYSQLI_ASSOC)) {
// This presumes you're storing your passwords in plain text.
// If you hashed your passwords or anything, you would have to do the same to $_POST['pword']
if ($_POST['pword'] == $col['pword']) {
// You could do anything here, but sessions are a way of keeping track of a user.
$_SESSION['userName'] = $_POST['uname1'];
$_SESSION['loggedIn'] = true;
}
}
}
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>
You would run a query along the lines of this:
$user_check_query = "SELECT * FROM useri1 WHERE uname=" . $_POST['uname'] . " AND pword=" . $_POST['pword'] .";";
And if the query returns a value, then they can proceed. If the query returns nothing, they cannot pass. As for the logic, look at the code you have created and see how to create if and else statements to handle the logic.
You need to do a SELECT query - something along the lines of
SELECT STRCMP('{$_POST['pword']}', pword) FROM useri1 WHERE uname = '{$_POST['uname']}'
This should return a value in the range [-1, 1] - if it is not 0, the password is wrong. If there is no rows, the user does not exist.
You need to think about SQL injections as well - but that could very well be an exercise for another day.

Categories