Okay, it was working before.... now all of a sudden it has stopped. i'm not sure why. The only thing i've added was a delete feature.. and after that it no longer submits. I can delete an entry though =D
php code for form
<?php
if (isset($_POST['submit'])){
$con = mysql_connect("localhost", "", "");
if (!$con){
die("Cannot connect:" . mysql_error());
}
$Firstname = $_POST['Firstname'];
$Email = $_POST['Email'];
$Prayer = $_POST['Prayer'];
//if there is no input these messages will come up//
if($Firstname==''){
echo "<script>alert('Please enter your name!')</script>";
exit();
}
if($Email==''){
echo "<script>alert('Please enter your email!')</script>";
exit();
}
if($Prayer==''){
echo "<script>alert('Please enter your prayer request!')</script>";
exit();
}
mysql_select_db("dxh6110",$con);
//if everything is good, information will be submitted to database
$sql = "INSERT INTO ChurchPrayer (Firstname, Email, Prayer) VALUES('$_POST[Firstname]','$_POST[Email]','$_POST[Prayer]')";
if(mysql_query($sql,$con)){
echo "<script>alert('Congratulations, You have successfully submitted your prayer requests. You will hear from us very soon!')</script>";
}
mysql_close($con);
}
?>
Oh, I'm aware that I should be using prepared statements to prevent SQL injection... but I'm not sure exactly what it is or what it looks like. I will definitely add them later, when I get further into my school project. Currently worried about the functionality..
not sure what else needs to be added... i'll add my delete.php
<?php session_start(); //starting the session?>
<?php
//connecting to database
$con = mysql_connect("localhost","","","dxh6110");
//defining variable
$delete_id = $_GET['del'];
//command to remove input from SQL DB
$query = "delete from ChurchPrayer where id='$delete_id'";
if(mysql_query($con,$query)){
echo "<script>window.open('view_prayers.php?deleted=User has been deleted!','_self')</script>";
}
?>
My admin log-in works, and when the admin logs in it brings them to a page which will allow them to view entries and delete entries made to the DB. Currently there are two, but when I try to add more requests.... they don't go to the DB. No errors are given when submit is clicked.
Firstly, ("localhost","xxx","xxx","xxx") doesn't do what you think.
mysql_connect() takes 3 parameters, not 4. The fourth is for something else. Four parameters are what one would use with mysqli_connect(), but those different MySQL APIs do not intermix with each other, so don't use that connection method if you're going to use mysql_ functions.
Consult:
http://php.net/manual/en/function.mysql-connect.php
http://php.net/manual/en/function.mysql-select-db.php
Do as you did in your other question:
$con = mysql_connect("localhost", "xxx", "xxx");
if (!$con){
die("Cannot connect:" . mysql_error());
}
mysql_select_db("your_db",$con);
Then this if(mysql_query($con,$query)){ the connection comes 2nd.
Plus, $_GET['del'] and ?deleted=User inspect that. Those are the two things that stood out for me.
If your delete link is ?deleted=XXX, it needs to be ?del=XXX - XXX being an example.
$_GET['del'] needs to match the parameter in the ?parameter in your method.
I.e.: view_prayers.php?del=XXX if view_prayers.php is the file you're using to delete with.
Plus, as mentioned in comments, this method is insecure.
It's best that you use mysqli with prepared statements, or PDO with prepared statements.
Related
I'm making a small project and I'm having some trouble with a php script. Basically, when they enter the text then click 'Enter' It loads to the 'insert.php'. The thing is, if they just visit the insert.php page without going to the main page It enters a plan table which could cause big problems.
Code:
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Can you help me fix this problem as It could cause a lot of troubles.
First you need to validate your $_POST variables by using isset().
If they are not submitted from a form, $_POST will be empty. Meaning that when a user try to type in the url, there won't be any post data and your SQL queries won't run.
2nd, you are subject to SQL injection since you are not escaping the content.
I'd suggest escaping each variable by using a prepared statement or mysqli_real_escape_string (less secure but better than nothing).`
if ( isset($_POST) && !empty($_POST['firstname']) && !empty($_POST['lastname']) && !empty($_POST['age'])) {
$con=mysqli_connect("localhost","info","info","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//simple example of escaping variables - BUT NOT AS SECURE AS PREPARED STATEMENT!!
$firstname = $con->real_escape_string($_POST['firstname']);
$lastname = $con->real_escape_string($_POST['lastname']);
$age = $con->real_escape_string($_POST['age']);
//With MySQLi it is best practice to use `prepere`, `bind_param` and `execute:
//or use PDO.
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$firstname','$lastname','$age')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
}
Lastly, you were missing the single quotes inside your $_POST variables.
Hope this helps!
This is pretty simple.
if(isset($_POST)):
//all of your code here
endif;
You have to check if $_POST exists to trigger your sql request
if (isset($_POST)){
//script
}
One of the first things that I see right off the top of my head is the fact that you are not checking to ensure that something has infact been typed Into your input box that passes the data to your other file. You can try to use isset() or array_key_exist(). Not to mention these are things that you should be doing anyway.
So I have a form and the form action= the file that contains the code below. I am getting a connection but the data is not saving. I formatted my form with input type textarea and the database with long text because I want to give the user as much space as they need to write their information. I think this might be my issue and have been searching the web to see if it is but I can't find anything that says it is or not. The weird part is that one time i did see an increase in the row of the database but when I checked it the row didn't contain the info I sent, it was blank.
<?php
session_start();
if (strlen($_POST['recipe'])|| strlen($_POST['usrtext'])||strlen($_POST['usrtxt']) ='0')
{header('location:shareerror.php');}
else
{
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("smqr",$connection)
or die("no connection to db");
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext''$usrtxt')");
header ('location:thanks.php'); }
?>
By mistake you are assigning instead of checking corrected statement is:
if (strlen($_POST['recipe'])|| strlen($_POST['usrtext'])||strlen($_POST['usrtxt']) ==0)
There is an error in your query
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext''$usrtxt')");
change this to
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,`usrtxt`)
VALUES('$recipe','$usrtext','$usrtxt')");
You are not setting the values for $recipe, $usrtext and $usrtxt
You are missing a comma in the values.
You are using strlen instead of isset
Also please take a look at How can I prevent SQL injection in PHP?. Your code is vulnerable to sql injection.
Here is the fixed code (with sql injection vulnerability intact!!)
<?php
session_start();
if (!isset($_POST['recipe'])|| !isset($_POST['usrtext'])||!isset($_POST['usrtxt']))
{
header('location:shareerror.php');
}
else
{
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("smqr",$connection)
or die("no connection to db");
$recipe = $_POST['recipe'];
$usrtext = $_POST['usrtext'];
$usrtxt = $_POST['usrtxt'];
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,'usrtxt')
VALUES('$recipe','$usrtext','$usrtxt')");
header('location:thanks.php');
}
?>
Also you didn't assign the variables used in the query.
$query=mysql_query("INSERT INTO seafood(`recipe`,`usrtext`,`usrtxt`)
VALUES('$recipe','$usrtext','$usrtxt')");
do that like this:
$recipe = $_POST['recipe'];
$usrtext = $_POST['usrtext'];
$urstxt = $_POST['usertxt'];
Then you can use the variables in the query
I tried it connection to database connection to database is successful but when i try to match user information with database it gives me a error NO database is selected
i tried it connecting to database using different method but nothing worked
<?php
//CREATING CONNECTION TO DATABASE
$con= new mysqli("localhost", "****", "***", "*****");
$con->select_db("lel_server_user_db_secured");
if(mysqli_connect_errno())
{
echo "Problem With connection to database Please contact administrator regarding this error";
}
/* RETURNS NAME OF DEFAULT DATABASE
if ($result = $con->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
*/
/*
$host="localhost";
$db_user="sky.xpert";
$db_pass="havefun344";
$database="lel_server_user_db_secured";
mysqli_connect($host,$db_user,$db_pass,$database) or die ("Failed to connect");
mysqli_select_db($database) ;
*/
session_start();
//GATHERING DATA FROM USER FORM
$email=$_POST["login"];
$pass=$_POST["pwd"];
//COMMANDING WHERE TO FIND MATCH FOR LGOIN INFORMATION
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
//IF MATCH FOUND THEN SETTING SESSION AND REDIRECTING IT TO LOGGED PAGE
if($match==1)
{
$_SESSION['loggedin'] = "true";
header ("Location: logged.php"); //REDIRECTING USER TO ITS HOMEPAGE
}
else //IF MATCH NOT FOUND THEN REDIRECTING IT BACK TO LOGIN PAGE
{
$_SESSION['loggedin'] = "false";
header ("Location: index.php");
}
//PERSONAL COMMENTS OR DETIALED COMMENTS
//PROBLEM WITH THIS SCRIPT GIVING OUTPUT ON LOGIN "NO DATABASE SELECTED"
//REFRENCE from http://www.dreamincode.net/forums/topic/52783-basic-login-script-with-php/
?>
You are initializing a connection to your database with mysqli. Then you try to do queries with mysql. Obviously, there is no connection with the database made through that library, and therefore it fails with an error. Change mysql_query to mysqli_query.
General note
Your current code is vulnerable to sql injection attacks, because you do not sanitize the input from the user before putting it in a query. Consider using prepared queries.
The database lel_server_user_db_secured may be not exist.
Content to your mysql:
mysql -hlocalhost -uusername -p
then input your password. After login, type command:
show databases;
check if lel_server_user_db_secured is in the result.
update1*
change the code below:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$query=mysql_query($veryfy) or die ( mysql_error() );
$match=0;
$match=mysql_num_rows($query);
to:
$veryfy="SELECT * FROM users WHERE Email='$email' Password='$pass'";
$result = mysqli_query($con, $veryfy) or die ( mysqli_connect_errno() );
$match=0;
$match=mysqli_num_rows($result);
var_dump($match);
In the first half of your program you have used mysqli and in the latter half mysql. Either use mysqli or mysql. I would recommend using mysqli in your entire program so that you are not vulnerable to SQL injection
you can simply do it by
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
there is no need to do $con->select_db("lel_server_user_db_secured"); again
and using mysqli isnt mean your code is safe ... your code is still vulnerable to SQL injection Use prepared statement instead or atleast mysqli_real_escape_string
You need to escape all request properly
and its possible that your database isnt exist so check that its exist first
AND you are mixing tow different API
you can not use MySQLi functions with MySQL_* function
I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.
I am trying to insert data into two different tables in the same database, if I try to insert it into one database, it works, however, once I insert the second query into my code ($desc_query) it won't update any table.
Here is my code:
$name= strip_tags($_POST['name']);
$l_name= strip_tags($_POST['last_name']);
$c_id = strip_tags($_POST['company_id']);
$a_d = strip_tags($_POST['add_description']);
$d_t = strip_tags($_POST['desc_text']);
$connect = mysql_connect('localhost','id','pass') or die ("couldn't connect!");
mysql_select_db('database_db') or die('could not connect to database!');
//inserting names
$job_query=mysql_query("INSERT INTO names VALUES ('', '$name', '$l_name')");
//inserting a new description if needed. (this is the part that ruins everything)
if($a_d == 'true'){
$desc_query=mysql_query("INSERT INTO descriptions VALUES ('','$c_id','$d_t')");
}
You might be having an issue where some characters (like ' and ") are breaking the SQL query (not to mention opening your application up for SQL injection attacks).
I would recommend sanitizing all user provided data like so:
$name = mysql_real_escape_string(strip_tags($_POST['name']), $connect);
$l_name = mysql_real_escape_string(strip_tags($_POST['last_name']), $connect);
...
$d_t = mysql_real_escape_string(strip_tags($_POST['desc_text']), $connect);
Always operate under the assumption that the user is going to enter something outlandish or malicious that may (or may not) break your SQL.
Have you tried to echo out the queries and then to run them directly on the database?
Without any more information about the database we can't really tell if the queries themselves are valid.