PHP error in mysql database selection - php

I wrote a code in PHP to connect with Mysql database and add data into it.. code is given below:
$dbhostname = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "rms_invoice";
function showDBMessage(){
if($_POST["name"] != NULL){
//came from register page
if(register()){
print("<br/>Registered successfully!!!");
} else {
print("<br/>Registration failed!!!");
}
}
}
function register(){
global $dbhostname,$dbusername,$dbpassword,$dbname;
// Create connection
$con=mysqli_connect($dbhostname,$dbusername,$dbpassword);
// Check connection
if (!mysqli_connect_errno()) {
print("MYSQL Connection established...<br/>");
echo "<br/>Successful: ".mysqli_get_host_info($con);
$selected = mysqli_select_db($con, $dbname);
if(false!==$selected){
$name = mysqli_real_escape_string($con, $_POST["name"]);
$username = mysqli_real_escape_string($con, $_POST["username"]);
$password = mysqli_real_escape_string($con, $_POST["password"]);
$address = mysqli_real_escape_string($con, $_POST["address"]);
$insertUserQuery="INSERT INTO USER(name,username,password,address) VALUES ('$name','$username','$password','$address')";
echo $insertUserQuery;
$result = mysqli_query($con, $insertUserQuery);
if ( false===$result ) {
printf("<br/>mysqli_connect_error: %s\n", mysqli_connect_error());
printf("<br/>mysqli_error: %s\n", mysqli_error($con));
} else {
echo "<h4>New User Added!!!</h4><br/>";
return true;
}
}else{
printf("<br/>Error while selecting database, error:%s\n",mysqli_errno($con));
}
} else {
print("<br/>Failed to connect to MySQL: "+mysqli_connect_error());
}
mysqli_close($con);
return false;
}
and the output is:
MYSQL Connection established...
Successful: localhost via TCP/IP
INSERT INTO USER(name,username,password,address) VALUES ('nitin','ndthokare','p','beed')
mysqli_connect_error:
mysqli_error: No database selected
Registration failed!!!
It is getting connected but database selection seems to be problem. (same query executes successfully through mysql cli).
I tried many possible corrections in code discussed on SO, but could not succeed.
Can anybody help me to find out the mistake?

if(false!==!$selected){
is extremely unusual operator (called "double negative") means you want to execute the following code block only if $selected is FALSE.
to make it much less confusing, write it without all these magic chants
if($selected){
or even omit this useless check completely.

Related

Something wrong with data insert

Good day,i am trying to insert data into mysql table using php its kinda working but i can't see data in phpmyadmin
<?php
$con=mysqli_connect('localhost','root','');
if(!$con)
{
echo("not connected");
}
if(!mysqli_select_db($con,'exam'))
{
echo 'db not selected';
}
$header = $_POST['header'];
$date = $_POST['date'];
$categ = $_POST['categ'];
$moder = $_POST['moder'];
$posttxt = $_POST['posttxt'];
$theme = $_POST['theme'];
$author = $_POST['author'];
$sql = "INSERT INTO postex (header,date,categ,moder,posttxt,theme,author) VALUES ('$header','$date','$categ','$moder','$posttxt','$theme','$author')";
if
(empty($header) || empty($date) || empty($categ) || empty($moder) || empty($posttxt) || empty($theme) || empty($author))
{
echo "<Br>feel the fields!!!";
}
else{
echo("<br>added,wait for redirect");
}
?>
Ok, before anymore wrong answers come up using mysql_, it's mysqli_query($con, $sql) that wasn't used to execute the query.
RTM http://php.net/manual/en/mysqli.query.php
and take care of that sql injection that you're leaving yourself open to, if/when you go live with this.
https://en.wikipedia.org/wiki/SQL_injection
with a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
while making sure the POST arrays do contain values (and the form uses a POST method with matching named inputs) and that there are no characters passing through that MySQL could complain about, for example: apostrophes.
Escape the data going in, in any respect.
Check for errors via PHP and the query:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
Nota:
You should first check if any of the fields are (not) empty, then execute the query.
I.e. and pseudo conditionals:
if(none empty and good to go){
// execute the query
}
else{
// do something else
}
Plus, if you're using your entire code inside the same file, being the form and php/mysql, then you should check if any of the POST arrays are set/not empty first. That will throw a few errors and give you undesired results.
<?php
function db(){
$servername = "servername";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
$conn->query("SET CHARACTER SET utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
$data=db();
$insert="INSERT INTO movies (bla1, bla2, bla3) VALUES (blavalue1, blavalue2, blavalue3)";
$dotaz=mysqli_query($data,$insert);
if($dotaz){
echo "OK";
}else{
echo "Wrong";
}
?>

SQL insert to MySQL doesn't work

I'm currently trying to insert username, pw to a DB, and check if the username already exists.
The problem is that the SQL (select) syntax doesn't work, nor does the (insert). I've checked around for a couple of hours in forums and Stackoverflow, and my current code is the following.
What might be the problem?
Thanks, Jimmie.
<?php
$servername = "localhost";
$username = "name";
$password = "pw";
$dbname = "dbaname";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ((isset ($_POST["identity"])) && (isset ($_POST["pin"])) && (isset ($_POST["token"])))
{
$identity = htmlspecialchars($_POST['identity'], ENT_QUOTES, "ISO-8859-1");
$pin = htmlspecialchars($_POST['pin'], ENT_QUOTES, "ISO-8859-1");
$token = htmlspecialchars($_POST['token'], ENT_QUOTES, "ISO-8859-1");
echo "$identity";
if($token == "xyz13D;A##:!#")
{
$result = $mysqli->query("SELECT `identity` FROM Users WHERE `identity` = '" . $identity . "'");
if($result->num_rows == 0)
{
echo "successCreat";
// Perform queries
mysqli_query($mysqli,"SELECT * FROM Users");
mysqli_query($mysqli,"INSERT INTO Users (identity,pin,userActivity, identityCreated) VALUES ('$identity', '$pin',1,now())");
}
else
{
echo "failureCreate";
}
}
else
{
echo"Wrong Key";
}
}
$mysqli->close();
?>
Assuming that identity is a primary key, then you can check the error flags after executing an INSERT query to see if an error occurred.
mysqli_query( $mysqli, "INSERT INTO ... " ); //< ... Represents query
if (mysqli_error( $mysqli )) {
echo "Failure";
}
else {
echo "Success";
}
Also, you should properly escape input as stated in the comments. In addition, you should check whether or not the connection attempt was successful using mysqli_connect_error.
Finally, there might be an issue in your SQL suntax which mysqli_error will also catch. A last possibility is that the POST data isn't being set properly and the code is being ignored completely.

query returns nothing after a particular result size using MYSQLI_USE_RESULT [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 1 year ago.
I've read for larger result sets I must use the MYSQL_USE_RESULT option when querying. This I do. However, the below PHP page is accessed via ajax and I receive 0 results once the known number of results reaches ~800. Before I reach this threshold, queries execute splendidly.
All queries work fine in phpmyAdmin.
What am I doing wrong?
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$database = "mydb";
$mypassword = "expectedPassword";
$receivedPassword =$_POST["pwd"];
if ($receivedPassword != $mypassword) {
print "credential failure";
} else {
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$myquery =$_POST["query"];
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
}
$res = $conn->query($myquery, MYSQLI_USE_RESULT);
$rows = array();
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
$conn->close();
print(json_encode($rows));
}
?>
This had nothing to do with memory. Turns out the relation between larger query results and failing was purely statistical.
The real problem was that there were occasionally special characters in the data stored in the database. For some reason (perhaps someone can explain) PHP just stopped--no errors, no nothing when a special character was encountered. The field with the special character has collation: utf8_general_ci. I would have never thought this would be an issue... Perhaps someone can explain this as well.
Adding:mysqli_set_charset($conn,'utf8'); before the query fixed my problem entirely.
Edit your php.ini to let your server use more memory. Change memory_limit =128M to your desire value or add ini_set('memory_limit', '-1'); to your php code but this will tell the server to use all the memory it wants.
Try to use this:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$database = "mydb";
$mypassword = "expectedPassword";
$receivedPassword =$_POST["pwd"];
if ($receivedPassword != $mypassword) {
print "credential failure";
} else {
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
$myquery =$_POST["query"];
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
$res = $conn->query($myquery, MYSQLI_USE_RESULT);
$rows = array();
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
$conn->close();
print(json_encode($rows));
}
}
?>
In //Check connection you put if function. First statement is die() if $conn is error. In else statement of same if function you've puted nothing. Bottom part of code need to be inside else statement to work.
Try it.
try replace this
while ($r = mysqli_fetch_assoc($res)) {
$rows[] = $r;
}
on this
if ($result = $conn->store_result()) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->free();
}
You use MYSQL_USE_RESULT to recive all rows from table?

No error, but still can't use 3 stored procedure in 1 pages php using database mysql

I have a script that checks an IP address from database, then checks if the IP address is unique or not. If the IP address is not unique, it saves the IP Address to IP_history on database. It's working very slowly, that's why I converted it to mysql stored procedure, but it doesn't run the same. It only runs the 1st procedure. I need it to run 3 procedures in a single page.
Here is my code:
$server = 'localhost'; // MySQL hostname
$username = 'xxx'; // MySQL username
$password = 'xxx'; // MySQL password
$dbname = 'xxx'; // MySQL db name
//$ipvisitor=$_SERVER['REMOTE_ADDR'];
if (isset($_GET['ip']) && $_GET['ip']) {
$ipvisitor = $_GET['ip'];
} else {
$ipvisitor = $_SERVER['REMOTE_ADDR'];
}
$db = new mysqli($server, $username, $password, $dbname);
if ($db->connect_errno) {
echo $db->connect_error;
}
if ($result = $db->query("CALL cekip('$ipvisitor')")) {
$db->error;
}
$dataip = $result->fetch_array();
$hitung = $result->num_rows;
if ($hitung == 0) {
echo "Tidak Ada Dalam Database";
} else {
$cekunik = $db->query("CALL cekhistory('$ipvisitor')");
$unik = $cekunik->num_rows;
if ($unik > 0) {
echo "Sudah Pernah Masuk";
} else {
echo $dataip['country'];
$addhistory = $db->query("CALL addhistory('$ipvisitor')");
}
}
Why is it only running one call?
And what is the best approach to fix the issue?

The same script in PHP in localhost doesn't working online

I upload my script in my server and I made a new database in the same server.
the connection with database is working, but when the two script check or insert new value on the database doesn't working, but in localhost yes!!
<?php
require 'client/facebook.php';
$app_id = "***";
$secret = "***";
$app_url = "***";
// Create our Application instance
///jump the code
////////////////////////////////
$sdb = "***";
$db = "***";
$userdb = "***";
$passdb = "***";
$dblink = mysql_connect($sdb,$userdb,$passdb);
$seldb = mysql_select_db($db);
$username = $username; //user data
$UIDfaceboook =$id; //UID USER FACEBOOK FROM API
$user_type ="aa"; //USER DATA
$connection =""; //variable for start function check UID
$checkUIDdb ="INATTESA"; //check if exist the UID facebook
$insertnewuser ="";
$loadspecific ="inattesa";
///
///CHECK CONNECTION WITH DATABASE
///
$mysqlConnection = mysql_connect($sdb, $userdb, $passdb);
if (!$mysqlConnection)
{
echo "NO DATABASE FOUND, CHECK USER, PASS, DB";
}
else
{
echo "connection with database is ";
echo $connection = "ok";
mysql_select_db($db, $mysqlConnection);
}
//////////////////////////THIS FUNCTION DOESN'T WORK ONLINE
if ($connection = "ok"){
$con=mysqli_connect($sdb,$userdb,$passdb,$db);
$check="SELECT * FROM tabletest WHERE UIDfacebook = '$UIDfaceboook'";
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "UID IN THE DATABASE ";
echo $checkUIDdb = "found";
}
else
{
echo "UID IN THE DATABASE ";
echo $checkUIDdb = "nofound";
}
}
///////////////THIS FUNCTION DOESN'T WORK ONLINE, and doesn't insert values
if($connection == "ok" && $checkUIDdb == "nofound"){
$username = strip_tags(mysql_real_escape_string($username));
$UIDfacebook = strip_tags(mysql_real_escape_string($UIDfaceboook));
$user_type = strip_tags(mysql_real_escape_string($user_type));
$sql = mysql_query("INSERT INTO `$db`.`tabletest` (`id`,`username`,`UIDfacebook`,`user_type`) VALUES ('','$username','$UIDfaceboook','$user_type');");
if($sql){
//The query returned true - now do whatever you like here.
echo $connection = "SAVE USERNAME, UID FACEBOOK AND USER TYPE ON DATABASE";
echo $loadspecific ="caricadati";
echo $insertnewuser = "yes";
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
}
}else{
echo $connection = " CORRECT LOGIN WITH FACEBOOK";
}
mysql_close($dblink);
//Close off the MySQL connection to save resources.
?>
the echo php on my server said " connection with database is okUID IN THE DATABASE nofound" so, I don't understand when the variable $connect, $checkUIDdb is working don't load the script for insert a new user... I try to add my UID facebook in my database to check if the script jump this step, but the script ignore the database... just said that...
maybe the first problem is on $check="SELECT * FROM tabletest WHERE UIDfacebook = '$UIDfaceboook'";
but in localhost works..
thank you very much, i don't know what I can do...
first error i saw was this one:
//////////////////////////THIS FUNCTION DOESN'T WORK ONLINE
if ($connection = "ok"){
i guess you should edit this to
if ($connection == "ok"){
so you ask if $connection has the value "ok" and not if the allocation of "ok" to $connection has been done successfully.
Second error could be a mixture of "mysql" and "mysqli"...
hth

Categories