PHP sending a post [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
I am currently trying to use PHP as a backend and MYSQL as my database to setup a simple PHP script that will send a friend request.
There are two parameters for a friend request in my MYSQL data base, From, Too. The Database name is send_friendreq and the table in that database is pending_req.
I have tried multiple ways of sending a post, including PostMan and a different addon but everytime I send the post, I get an error from my PHP code which is "Failed". From my understanding this means that it is connecting to the database fine, but it's not actually sending the data too the Database.
I'm not sure if I have the database set up wrong, or if my PHP is wrong but any help would be extrememly appreciated.
Here is my code for the PHP backend
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
}
if (isset($_POST['Username']) && isset($_POST['FriendReq']))
{
$username = $_POST['Username'];
$usernamebeingreq = $_POST['FriendReq'];
//$sqlCheck = "SELECT Username FROM Users WHERE Username = '" . $usernamebeingreq . "'";
//$resultCheck = mysqli_query($con, $sqlCheck);
//if(!$resultCheck)
//{
//echo "Invalid Username";
//}
//else
//{
$sql="INSERT INTO pending_req (To, From) VALUES ('$usernamebeingreq', '$username')";
$result = mysqli_query($con, $sql);
if(!$result)
{
echo 'Failed';
}
else
{
echo 'Friend added!';
}
//}
}
else
{
echo 'Missing Parameters';
}
?>
If you are in need of my database information, I can reveal that!

from and to are reserved words in SQL you have to add backticks arrond:
$sql="INSERT INTO pending_req (`To`, `From`) VALUES ('$usernamebeingreq', '$username')";
or better rename the column.
Hint: use prepared statement. it is much more safty.

Related

mysqli_query() generating query error [duplicate]

This question already has answers here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
I am trying to store form data into database using mysqli but it is generating query error my code is given below....
When ever I try to submit the database connection is generating.. the $_POST is working perfectly.. the error only generating by mysqli_query..
<?php
$name = $_POST["firstname"] . " " . $_POST["lastname"];
$email = $_POST["email"];
$happen = $_POST["whendidhappen"];
$howlong = $_POST["howlong"];
$howmany = $_POST["howmany"];
$describe = $_POST["describe"];
$whattheydid= $_POST["whattheydid"];
$seenmycat = $_POST["seenmycat"];
$anythingelse = $_POST["anythingelse"];
$dbc = mysqli_connect('localhost','root','','abductionreport')
or die('Database connection error');
$query = "INSERT INTO abductionform (firstname, lastname, email,whendidhappen, howlong, describe, whattheydid, seenmycat,anythingelse)VALUES('$name','$name','$email','$happen','$howlong', '$howmany','$describe','$whattheydid', '$seenmycat','$anythingelse')";
$result = mysqli_query($dbc,$query) or die ("Query Error");
mysqli_close($dbc);
?>
<h3>Aliens Abducted Me - Report an Abduction</h3>
<p>Thanks for Submiting the form.</p>
<?php
echo "$name it happend to you on $happen it take $howlong <br>";
echo "Number of aliens: $howmany<br>";
echo "Describe: $describe<br>";
echo "What they did to you: $whattheydid<br>";
echo "Have you seen my cat: $seenmycat<br>";
echo "Anything else : $anythingelse<br>";
echo "Your Email Address is : $email<br>";
?>
DESCRIBE is a mysql keyword. Wrap the column name in backticks. For that matter wrap your table and all columns in backticks. Always check that $_POST elements exist with isset () before trying to access them. Use mysqli prepared statements with placeholders for improved security. Always perform error checking BEFORE posting to SO.
You also have 9 columns and 10 values in your query - this will cause a failure every time.

The insert query is not working. and unable to locate the error as well [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I have issue with the query. i don't know why its not working,
it always shows , there is an error, and do not insert data into table, although it is collecting data from form.
there is no error or warning notification but it chooses the else option from if condition and does not insert data into table, don't know why.
<?php
$con=mysqli_connect('localhost','root','','flentox');
if(mysqli_connect_error($con))
{
echo "there is an error in connection";
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$area=$_POST['select'];
$address=$_POST['address'];
$eaddress=$_POST['eaddress'];
$query= mysqli_query($con, "INSERT INTO order(Fname,Lname,Email,Phone,Area,Address,Eaddress) VALUES(`$fname`,`$lname`,`$email`,`$phone`,`$area`,`$address`,`$eaddress`)");
if ($query) {
echo "order confirm";
}
else {
echo "There is an error";
}
?>
Your query is not correct, you don't need to use ( `` ) in VALUES. Don't forget to check if your values is empty or not.
So if there is no data has come from $_POST, your query also will be crashed.
Also don't forget about SQL injections. It is not recommended to insert $_POST or $_GET data immediately in query. Use Prepared Statements.
Try this.
$fname = (empty($_POST['fname']) ? 'default value' : $_POST['fname']);
.......... (for other params too).
"INSERT INTO order (`Fname`,`Lname`,`Email`,`Phone`,`Area`,`Address`,`Eaddress`)
VALUES('".$fname."','".$lname."','".$email."','".$phone."','".$area."','".$address."','".$eaddress."')";
Also to show your errors, run this code at the very top of the php file -
error_reporting(1);

mysqli_query doesnt seem to execute correctly [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
This one has had me stumped for a couple of days. I have a basic PHP script to submit a user registration form. I just cant see what I am doing wrong in this instance the web server is running PHP 7.0 and there are no errors in the logs.
<?php
require_once('connect.php');
if(isset($_POST) && !empty($_POST)){
$username = mysqli_real_escape_string($connection, $_POST['username']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password =md5($_POST['password']);
$sql = "INSERT INTO 'login' (username, email, password) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($connection, $sql);
if($result){
echo "User Rego Secusseflllgk";
}else{
echo "User rego faile";
}
}
?>
I saw a couple of these already but they seemed to be to do with using both myslq and mysqli and others appeared to not be first connection to the DB. Any help would be much appreciated. I am recieving the User Rego Failed echo
You probably want use the backtick ` instead of a single quote ' to wrap your table name.
INSERT INTO `login`
When a query fail, it's useful to print the error message. You can do it with mysqli_error:
echo mysqli_error($connection);
Use table name without single quote and try to check mysqli error with mysqli_error($connection) just after $result.

No Database Selected Php

This is a somewhat simple task, I am trying to compare a username to that in the database. I am testing it out in a single php file before I do it properly. My code is below. Basically I have a user, which is in the database and I am checking if it is in there.
<?php
$db_connect = mysql_connect("127.0.0.1", "root", "anwesha01", "mis");
//Check if connection worked.
if(!$db_connect)
{
die("Unable to connect to database: " . mysql_error());
}
//For testing purposes only.
else
{
echo "Database connect success!";
}
$user = "alj001";
$query = "SELECT Username FROM `user` WHERE `Username` = '".$user."'";
//What is being passed through the database.
echo "<p><b>This is what is being queried:</b> " . $query;
//Result
if (mysql_query($query, $db_connect))
{
echo "<br> Query worked!";
}
else
{
echo "<p><b>MySQL error: </b><br>". mysql_error();
}
?>
The result I get is:
Database connect success!
This is what is being queried: SELECT Username FROM user WHERE Username = 'alj001'
MySQL error: No database selected
First I had my mysql_query without the $db_connect as it is above, but I put it in and I still get "no database selected".
Ive looked at the w3c schools for the mysql_query function, I believe I have done everything correctly. http://www.w3schools.com/php/func_mysql_query.asp
Because you haven't called mysql_select_db. Note that the 4th parameter to mysql_connect is not what you think it is.
That said, you really should be using PDO or mysqli, not the plain mysql_ functions, since they're deprecated.

querying two database in php at a time

Whenever a user submits the registration form I am updating two database at a time. The first database easily gets updated but there is no effect in the second database. Below is my php code
<?php
$host="localhost";
$user="aru";
$password="arus";
$ur="asus";
$passord="asus";
$db="regster";
$dbn="nsltr";
$sq=mysql_connect($host,$user,$password) or die ('mysql connecction failed'.mysql_error());
mysql_select_db($db, $sq) or die('mysql cannot select database'.mysql_error());
$dbh2 = mysql_pconnect($host, $ur, $passord, true) or die ('mysql connecction failed'.mysql_error());
mysql_select_db($dbn, $dbh2) or die('mysql cannot select database'.mysql_error());
if(isset($_POST['btnSubmit1'])){
$fullName=htmlentities(mysql_real_escape_string($_POST['nme']));
$emailID=htmlentities(mysql_real_escape_string($_POST['emil']));
$bc=htmlentities(mysql_real_escape_string($_POST['bch']));
$bn=htmlentities(mysql_real_escape_string($_POST['bnc']));
$m=htmlentities(mysql_real_escape_string($_POST['mobe']));
$em=htmlentities(mysql_real_escape_string($_POST['empy']));
$a=htmlentities(mysql_real_escape_string($_POST['ofadrs']));
$me=htmlentities(mysql_real_escape_string($_POST['msge']));
$doj=date("Y-m-d");
$sql="insert into rgst values('$emailID', '$fullName', '$bc', '$bn', '$m', '$em', '$a', '$me', '$doj')";
$rndnm= uniqid();
$log="insert into nwsletter values('$emailID', '$fullName', '$rndnm')";
if((!(mysql_query($sql,$sq))) AND (!(mysql_query($log,$dbh2))) ){
echo '<script language="javascript">alert("Sorry!!! it seems you are already registered");</script>';
}
else{
echo '<script language="javascript">alert("Successfully registered.. Please check your mail address for password and other details");</script>';
}
}
?>
By the above code I am able to update register database but there is no change in nsltr database and also no error pops up after executing the codes. Please help, am new to php. Thanks in advance
It looks like your two databases are on the same server, and it looks like your database credentials grant access to both.
In this case you can use the same connection to update both data bases; simply qualify the database names in your SQL.
For example,
insert
into regstr.rgst
values ('$emailID', '$fullName', '$bc', '$bn', '$m', '$em', '$a', '$me', '$doj')
insert
into nsltr.nwsletter
values ('$emailID', '$fullName', '$rndnm')
You can even JOIN tables in different databases as long as they're on the same server and your username has access to both of them.
You should use the _num_rows() call right after running each query, to ensure it actually inserted the number of rows you were expecting.
I'll leave it to somebody else to whine at you about how freakin' dangerous it is to use the obsolete mysql_ API in a production application.
don't use mysql_ API, instead use mysqli_API. Below is your code using mysqli_ API. Hope it works for you
<?php
$host="localhost";
$user="aru";
$password="arus";
$ur="asus";
$passord="asus";
$db="regster";
$hst="localhost";
$ur="asus";
$passord="asus";
$dbn="nsltr";
$sq=mysqli_connect($host,$user,$password,$db);
if (mysqli_connect_errno($sq))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['btnSubmit1'])){
$fullName=htmlentities(mysql_real_escape_string($_POST['nme']));
$emailID=htmlentities(mysql_real_escape_string($_POST['emil']));
$bc=htmlentities(mysql_real_escape_string($_POST['bch']));
$bn=htmlentities(mysql_real_escape_string($_POST['bnc']));
$m=htmlentities(mysql_real_escape_string($_POST['mobe']));
$em=htmlentities(mysql_real_escape_string($_POST['empy']));
$a=htmlentities(mysql_real_escape_string($_POST['ofadrs']));
$me=htmlentities(mysql_real_escape_string($_POST['msge']));
$doj=date("Y-m-d");
$sql="insert into regster.rgst values ('$emailID', '$fullName', '$bc', '$bn', '$m', '$em', '$a', '$me', '$doj')";
$rndnm= uniqid();
$log="insert into nsltr.nwsletter values ('$emailID', '$fullName', '$rndnm')";
if((!(mysqli_query($sq,$sql)))){
echo '<script language="javascript">alert("Sorry!!! it seems you are already registered");
</script>';
}
else{
mysqli_close($sq);
$qq=mysqli_connect($hst,$ur,$passord,$dbn);
if (mysqli_connect_errno($qq))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
if((!(mysqli_query($qq,$log)))){
echo "Failed to connect to MySQL: " . mysqli_error($qq);
}
else{
echo '<script language="javascript">alert("Successfully registered.. Please check your mail address for password and other details");
</script>';
}
}
}
}
?>
Remember, you have to pass all the values for all the fields otherwise you might get "Column count doesn't match value count at row 1" error which will prevent from updating the databases

Categories