querying two database in php at a time - php

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

Related

PHP sending a post [duplicate]

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.

mysql php displays results but not inserting into database

I stripped down query for only one insert
<?php
session_start();
include 'cstring.php';
$title="";
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
$title=$_POST['title'];
$query=mysqli_query($con,"insert into blogpages(blogpagetitle) values('".$title."')");
if($query){
$bloga="sucessfully added a new blog";
echo $bloga;
}
else {
echo mysqli_error($con); // if using mysqli do not use mysql in between
}
}
mysqli_close($con);
?>
is there something wong in this code that it doesnt insert into mysql
table structure
1.bpid int(50)--------------null-no default-none autoincrement
2.blogpagetitle------------varchar(255) utf16_general_ci
3.datemade-------------timestamp current time stamp
4.blogpagedescription---------text utf16_general_ci
5.blogbody----------------longtext utf16_general_ci
6.blogpageextended------------ text utf16_general_ci
TIP
Sanitize variables, Use mysqli_real_escape_string()
When you are not able to debug your code, echo every possible stuff and die the rest code.
For example here, echo if there is error in DB connection, echo the query to see if it is correct, echo the result of query execution, echo if there is some error!
You should be using echo mysqli_error($con) to get the error message rather than mysql_error().

So i'm trying to have it check to see if the steamid64 all ready exists before inserting but it just inserts any way?

So i'm trying to have it check to see if the steamid64 all ready exists before inserting but it just inserts any way?
i'm not good with PHP here.
<?php
$con=mysqli_connect("localhost","user","pass","Gmod");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SteamID64 = mysqli_real_escape_string($con, $_POST['SteamID64']);
$enable = mysqli_real_escape_string($con, $_POST['enable']);
$sql="SELECT * FROM Loading (SteamID64, enable) WHERE SteamID64='$SteamID64'";
if(mysql_num_rows($sql)>=1) {
echo'<center>The music is already disabled!</center>';
}
else {
$sql="INSERT INTO Loading (SteamID64, enable)
VALUES ('$SteamID64', '$enable')";
}
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<center>The music will not play when you connect.</center>";
mysqli_close($con);
?>
i got this off some forums and w3schools.com
and edited it.
Ok so i did this but its still just inserting the data?
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
$con=mysqli_connect("localhost","root","server","Gmod");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$SteamID64 = mysqli_real_escape_string($con, $_POST['SteamID64']);
$enable = mysqli_real_escape_string($con, $_POST['enable']);
mysqli_query($con,"SELECT * FROM Loading WHERE SteamID64='$SteamID64'");
if(mysqli_num_rows(mysqli_query)>=1) {
echo'<center>The music is already disabled!</center>';
}
else {
mysqli_query($con,"INSERT INTO Loading (SteamID64, enable)
VALUES ('$SteamID64', '$enable')");
}
echo "<center>The music will not play when you connect.</center>";
mysqli_close($con);
?>
Apart from the fact that you cannot mix mysql_* and mysqli_* functions like that (pick one, mysqli_* and stick to that), you have an error in your sql:
SELECT * FROM Loading (SteamID64, enable) WHERE SteamID64='$SteamID64'
^^^^^^^^^^^^^^^^^^^ this should not be here
You need to change that to:
SELECT * FROM Loading WHERE SteamID64='$SteamID64'
You can have mysqli throw exceptions so that it tells you exactly what went wrong when it goes wrong. Just add this to the top of your script:
mysqli_report(MYSQLI_REPORT_STRICT);
Another problem you have, is that the execution of your second query should be inside the else part of the previous condition.
And as #FabrícioMatté already mentioned, you actually need to execute your query using mysqli_query(), just setting the string does not do anything.

How to fix php adding a plain row

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.

issue when inserting data to database

My code doesn't insert any records to mysql. What is wrong? I am really confused.
I have designed a form and I want to read data from text box and send to the database.
<?php
if(isset($_post["tfname"]))
{
$id=$_post["tfid"];
$name=$_post["tfname"];
$family=$_post["tffamily"];
$mark=$_post["tfmark"];
$tel=$_post["tftell"];
$link=mysql_connect("localhost","root","");
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("university",$link);
$insert="insert into student (sid,sname,sfamily,smark,stel) values ($id,'$name','$family',$mark,$tel)";
mysql_query($insert,$link);
}
mysql_close($link);
?>
You'd better to put quotation mark for id, mark and tel after values in your query. Also as #Another Code said, you must use $_POST instead of $_post in your code. Try this and tell me the result:
<?php
if(isset($_POST["tfname"])) {
$id=$_POST["tfid"];
$name=$_POST["tfname"];
$family=$_POST["tffamily"];
$mark=$_POST["tfmark"];
$tel=$_POST["tftell"];
$link=mysql_connect("localhost","root","");
if (!$link) {
die('Could not connect: ' . mysql_error());
} else {
mysql_select_db("university",$link);
$insert="insert into student
(sid,sname,sfamily,smark,stel) values
('$id','$name','$family','$mark','$tel')";
mysql_query($insert,$link) or die (mysql_error());
mysql_close($link);
}
} else {
die('tfname did not send');
}
?>
Use mysql_query($insert,$link) or die (mysql_error()); to fetch the error message.
With the code you've provided it could almost be anything - to do some tests... have you echo'd something to confirm you are even getting the tfname in POST? Does it select the database fine? Do the fields $id, $mark, and $tel need single quotes around them as well? We need to know more about where the code is not working to provide more help but that snippet appears as though it should be running, in the interim, please use some echo's to narrow down your problem!
Try to run the generated sql query in the sql query browser. Get the query by "echo $insert" statement.
change the $insert to:
$insert="insert into student (sid,sname,sfamily,smark,stel) values ($id,'".$name."','".$family."','".$mark."','".$tel."')";
further set ini_set('display_errors',1) so that php displays the error messages as required.
Lastly, whenever doing a mysql query, try to use or die(mysql_error()) in the query so that if somethings wrong with mysql or syntax, we are aware.
$q = mysql_query($query) or die(mysql_error());

Categories