a query is inserted from PHPMYAdmin but not from PHP - php

i'm writing a php code to insert form values in a forum values
$dbServer = mysql_connect("localhost" , "root", "") ;
if(!$dbServer) die ("Unable to connect");
mysql_select_db("kfumWonder");
$name= $_POST['name'] ;
$password= md5($_POST['password']);
$email= $_POST['email'] ;
$major= $_POST['major'] ;
$dateOfBirth=$_POST['dateOfBirth'] ;
$webSite = $_POST['website'];
$joinDate= date("Y m d") ;
$query = "INSERT INTO user (name, password, email, major, dob, website, join_date)
Values ('$name', '$password', '$email', '$major', '$dateOfBirth',
'$webSite' , '$joinDate')" ;
//echo $query ;
$result = mysql_query($query) ;
if (! $result )
echo " no results " ;
this works perfectly fine when i took the printed query and run it in PHPMyAdmin but when i run this code nothing happens

Your POST vars need to be escaped if you do not have magic quotes on like this mysql_real_escape_string($_POST['blah']). Even if magic quotes is on, you should strip slashes, or turn off magic quotes in the cofig, and re-escape them with mysql_real_escape_string. Or use PDO to do database entries as it handles this for you.
Also, to see what your errors are, you could call your query like this:
if (!$result = mysql_query($query)) echo mysql_error();

Related

PHP Code executing but not inserting data?

I've followed a year old online tutorial of Unity Client - PHP Server - Database integration. The code seems to execute fine, it reaches the 'echo"Success"' line etc perfectly.
However when I look at my database, there is nothing there. Its blank, and I have no idea why.
Note: The online tutorial used mysql... whereas I'm using the (non-depracted) mysqli... but there didn't seem to be that much of a difference, but I'm a total rookie at PHP coding, only having minimal experience at it so it is very possible I'm wrong?
<?php
/**
* Created by PhpStorm.
* User: Josh
* Date: 09/04/2016
* Time: 14:11
*/
$Username = $_REQUEST["Username"];
$Password = $_REQUEST["Password"];
$Hostname = "localhost";
$DBName = "statemilitaryrpdb";
$User = "root";
$PasswordP = "";
$link = mysqli_connect($Hostname, $User, $PasswordP, $DBName) or die ("Can't Connect to DB");
if (!$Username || !$Password) {
echo "Empty";
} else
{
$SQL = "SELECT * FROM accounts WHERE Username = '" . $Username ."'";
$Result = #mysqli_query($link, $SQL) or die ("DB ERROR");
$Total = mysqli_num_rows($Result);
if($Total == 0)
{
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
$SQL1 = mysqli_query($link, $insert);
$Result2 = #mysqli_query($link, $SQL) or die ("DB ERROR");
echo(mysqli_num_rows($Result2));
}
else
{
echo"Username Already Used";
}
}
mysqli_close($link);
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Answer: Username and Password are the fields but you are trying to insert Username, Password and 0
Suggestion: Do more than just MD5 encryption, that is SUPER easy to decrypt.
Edit:
Also like #andrewsi said in the comments if your only going to check if its empty, than anyone could SQL inject your database and drop your tables or make changes. Make sure that you are filtering your inputs correctly.
Firstly, your query have only 2 columns, but you are inserting 3 values:
$insert = "INSERT INTO 'accounts' ('Username', 'Password') VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)";
Columns
Username
Password
Values to insert
$Username
md5($Password)
0
Thus, not all the values will be inserted.
Secondly, for MySQL related names, you need to use back ticks instead of single-quote.
Thus, this:
INSERT INTO 'accounts'
Should be:
INSERT INTO `accounts`
Thirdly, your code is vulnerable to MySQL Injection, you should prevent it using mysqli_real_escape_string():
$Username = mysqli_real_escape_string($link, $_REQUEST["Username"]);
$Password = mysqli_real_escape_string($link, $_REQUEST["Password"]);
Tip: You shouldn't suppress error messages:
#mysqli_query($link, $SQL)
Remove # to enable error reporting. It's very useful in diagnosing syntax errors.
Also, you shouldn't use md5() to hash passwords, as it's not very secure. Use password_hash and password_verify instead.
In debug mode, never use # to suppress errors, ie. #mysqli_query. Also or die("DB ERROR") isn't very descriptive. Even if that resolves, what good does DB ERROR provide you? Instead, use or die( mysqli_error($link) ) to see what's really going on with the query.
You also have 3 values to be inserted, but only 2 columns represented in the query statement:
('Username', 'Password') // 2 columns
VALUES ('" .$Username . "', MD5('" . $Password . "'), 0)"; // 3 values
What column is 0 being inserted into? This value needs to be represented by a column.
And a table/column name should never be wrapped with quotes; only ticks `accounts`

mysqli_query insert not generating any response, the connection is working, but no data is inserted [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 7 years ago.
This is the code in my PHP script on a very basic html page with a form. I have tried every possible variation of single quotes, double, single and double for the values. I didn't get any response at all. I have tested to make sure the connection is made, but nothing is inserted in the DB. I just don't know what I'm doing wrong.
// Check our connection
if (mysqli_connect_errno($con)) {
print_r("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST["submit"])){
$name = $_POST['name'];
$company = $_POST['company'];
$email = $_POST['email'];
$comment = $_POST['comment'];
// Insert our data
$query = mysqli_query("INSERT INTO 'contacts' ('id','name', 'company', 'email', 'comment') VALUES ('','$name', '$company', '$email', '$comment')", $con);
$result = ($query);
if( $result )
{
print_r('Success');
}
else
{
print_r('Query Failed');
}
mysqli_close($con);
}
Your order is inverted, http://php.net/manual/en/mysqli.query.php.
connection first, then query.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
You also incorrectly used single quotes around the column names; those should be backticks; When to use single quotes, double quotes, and backticks in MySQL.
Additionally you should never pass user input directly to SQL. This is how injections occur. You should look into using prepared statements. How can I prevent SQL injection in PHP?
if (mysqli_connect_errno($con)) {
print_r("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST["submit"])){
$name = mysqli_real_escape_string($con, $_POST['name']);
$company = mysqli_real_escape_string($con,$_POST['company']);
$email = mysqli_real_escape_string($con,$_POST['email']);
$comment = mysqli_real_escape_string($con,$_POST['comment']);
// Insert our data
$query = mysqli_query($con, "INSERT INTO `contacts` (`name`, `company`, `email`, `comment`) VALUES ('$name', '$company', '$email', '$comment')");
if($query) {
print_r('Success');
} else {
print_r('Query Failed');
}
mysqli_close($con);
}
You don't need to use apostrophe (') for your table and column name. Remove the apostrophe in your contacts table. You can use backticks (`) for column names.
$query = mysqli_query($con, "INSERT INTO contacts (id, name, company, email, comment)
VALUES ('','$name', '$company', '$email', '$comment')");
You are also prone to SQL injections, so use *_real_escape_string.
$name = mysqli_real_escape_string($con, $_POST['name']);
$company = mysqli_real_escape_string($con, $_POST['company']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$comment = mysqli_real_escape_string($con, $_POST['comment']);
While you are at it, using mysqli_* API, you might want to check on prepared statement.

MySQL - PHP form to insert values into table?

I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);

Error with MySQL Query

Okay, I must be an idiot, because this is my 3rd question for today.
Here's my code:
date_default_timezone_set("America/Los_Angeles");
include("mainmenu.php");
$con = mysql_connect("localhost", "root", "********");
if(!$con){
die(mysql_error());
}
$usrname = $_POST['usrname'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
mysql_select_db("`users`, $con) or die(mysql_error()");
$query = ("INSERT INTO `users`.`data` (`id`, `usrname`, `fname`, `lname`, `email`, `password`)
VALUES (NULL, '$usrname', '$fname', '$lname', '$email', 'password'))");
mysql_query('$query') or die(mysql_error());
mysql_close($con);
echo("Thank you for registering!");
I always get the error returned as: "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 '$query' at line 1.
Help a newbie. I'm about to stab my monitor.
1) On this line:
mysql_select_db("`users`, $con) or die(mysql_error()");
Should be:
mysql_select_db("users", $con) or die(mysql_error());
Right now you have PHP code inside the string you're sending as the database name.
2) On this line:
mysql_query('$query');
By using single quotes, the literal string $query will be sent rather than the contents of a variable called $query. Use either mysql_query($query) or mysql_query("$query");
Also, where you create $query, and where you echo the success message, the parentheses around the string are unnecessary.
WITHIN $query, you have too many closing parentheses. You also fail to escape any of the input, so if someone writes something nasty in your form (like anything with a single quote character), it'll break your query.
mysql_query($query) or die(mysql_error());
uneeded quotes around your $query variable.
single quotes (') do not allow you to embed variables, while double quotes (") do.
mysql_query('$query') => mysql_query("$query")
How to fix the SQL-injection hole
Change this code
coding horror
$usrname = $_POST['usrname'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
Into this
$usrname = mysql_real_escape_string($_POST['usrname']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);

php form script

I'm very new to PHP and am having some trouble. I have a form using HTML which is action=.php method=post
The form is using text boxes and select options, I'm not sure if it makes a difference in sqldatabase. I've tried about 30 different combinations of this script and can only get a connect successfully message but nothing is posted.
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user");
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
mysql_close();
php?>
try to execute your query
mysql_query($sql);
EDIT: I see you are doing this:
$sql = 'SELECT bla bal $variable';
PHP will not parse the variable. The right way:
$sql = "SELECT bla bla $variable"; // valid
$sql = "SELECT bla bla {$variable}"; // also valid
$sql = 'SELECT bla bla '.$variable; // also valid
your closing php tag is not correct, it should be
?>
rather than
php?>
Also u r not executing your query using:
mysql_query('your query here');
this might cause the problem.
Your variables are not interpreted by PHP. If you want variable to be parsed in string, it should be wrapped in double-quote (")
It may fail if any of your posted data contains some quote character, so you must apply mysql_real_escape_string to all of them.
I hope that database connection credentials are not real you posted here? :D
You said that your form contains "action=.php" literally, you have to turn it into :
<form name="form_name" method="post" action="your_script.php">
You need to execute the query too:
mysql_query($sql, $link);
you should also check whether POST was really sent:
if (!empty($_POST)) {
// ... your code here
}
next thing: you don't need closing tag ?> if your *.php file consist only PHP code - end of file is also correct end of PHP block of code - it's "good-to-have" habit, because in some cases it helps you to avoid error: "Cannot add/modify header information - headers already sent by..."
next problem - wrong way of inserting variables into string:
$sql = 'INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES'
. '(\'\', \'$FName\', \'$LName\', \'$Phone\', \'$EmailAddress\', \'$Month\', \'$Day\', \'$Year\', \'$Username\', \'$Password\')';
correct way:
$sql = "INSERT INTO Members (ID, FName, LName, Phone, EmailAddress, Month, Day, Year, Username, Password) VALUES (null, '$FName', '$LName', '$Phone', '$EmailAddress', '$Month', '$Day', '$Year', '$Username', '$Password')";
more info here
next - as Deniss said, instead of:
$FName = $_POST["FName"];
should be:
$FName = mysql_real_escape_string($_POST["FName"]);
actually you should fist check weather magic quotes gpc are on or off:
if (get_magic_quotes_gpc()) {
if (!empty($_POST)) {
array_walk_recursive($_POST, 'stripslashes_value');
}
}
function stripslashes_value(&$value) {
$value = stripslashes($value);
}
without this you could have problem with double \\ inserted into db (it depends on your server configuration)
and last but not least: as Robert said you miss one more important thing:
mysql_query($sql);
I think your error because your have not call mysql_query function
can try my code edit
<?php
$link = mysql_connect('everybodyslistcom.ipagemysql.com', 'accounts', 'accounts');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db("user",$link);
$FName = $_POST["FName"];
$LName = $_POST["Lname"];
$Phone = $_POST["Phone"];
$EmailAddress = $_POST["EmailAddress"];
$Month = $_POST["Month"];
$Day = $_POST["Day"];
$Year = $_POST["Year"];
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$sql = "INSERT INTO Members SET FName='{$FName}', LName='{$LName}', Phone='{$Phone}', EmailAddress='{$EmailAddress}', Month='{$Month}', Day='{$Day}', Year='{$Year}', Username='{$Username}', Password='{$Password}'";
// Call Function mysql_query insert new record in mysql table
mysql_query($sql,$link);
mysql_close($link);
?>
Comment for me if your have problem :) or notes of apache services
good day

Categories