I am trying to connect to a db - php

I am trying to connect to a db but I keep getting an error that pops up every chance I get to change the db or connection string . I am currently using php mysqli and wamp will not show any error with the connection itself .
calc.php:
class Login {
var $con;
function __construct($con){
$this->con = $con;
}
function try_connecting(){
$connecting = true;
if($connecting){
if(!$this->con){
die ("Could not connect") . $this->con->connect_errno;
} else {
echo "connected";
}
} else {
return $connecting;
}
}
function try_login(){
if(try_connecting()){
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
if($rows == 1){
echo "true";
} else {
echo "not user";
}
}
}
}
Here is the test.php:
<?php
include("calc.php");
$u = $_POST['username'];
$p = $_POST['pwd'];
$con = mysqli_connect("localhost","root","","rdb");
$form = new Login($con);
$form->try_connecting();
$form->try_login();
?>
connection string error Unknown database

You forgot to run this query
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
Try to add
$this->con->query($q)
between the lines above

Related

having problem with mysqli_query, return NULL but the query works in phpmyadmin

I'm tring to retrive information from a database while a user send Login command from iOS app.
To test this function i'm launching my php page manually (ex. http://www.testdatabase.com/LoginFunctions.php) and forcing username programmatically.
The problem is that mysqli_query return NULL value. if i use "or die(mysql_error()" nothing happens. Even if i use mysqli_num_rows return 1, but $result is still empty.
So when mysql_fetch_assoc is been executed the programm crashes without showing any error.
Any idea? Thanks
<?php
// Create connection
$con=mysqli_connect("localhost","super","super","testdb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$action = "login";
$username = "Peperoncino";
$response = array();
if ($action == "login")
{
$query = "SELECT psw AS pswrd,id FROM Activities WHERE nome = 'Peperoncino' LIMIT 1";
if ($result = mysqli_query($con, $query))
{
$values = mysql_fetch_assoc($result);
$password = $values['pswrd'];
$response["password"] = $password;
$response["message"] = "Get information from db";
}
else
{
echo "err";
}
echo json_encode($response);
}
// Close connections
mysqli_close($con);
?>
You are using the deprecated mysql_fetch function.Use the new one
<?php
// Create connection
$con=mysqli_connect("localhost","super","super","testdb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$action = "login";
$username = "Peperoncino";
$response = array();
if ($action == "login")
{
$query = "SELECT psw AS pswrd,id FROM Activities WHERE nome = 'Peperoncino' LIMIT 1";
if ($result = mysqli_query($con, $query))
{
$values = mysqli_fetch_assoc($result);
$password = $values['pswrd'];
$response["password"] = $password;
$response["message"] = "Get information from db";
}
else
{
echo mysqli_error($conn);
}
echo json_encode($response);
}
// Close connections
mysqli_close($con);
?>

"Can't use function return value in write context" when using mysqli_num_rows()

I've been working on adding users to my database and I tried to do something to check if login is already occupied. If it's not, PHP should add the user to database, else give alert that login is already used. Here's my code:
<?php
$servername = 'localhost';
$username = 'wiktor';
$password = 'wiktor';
$database = 'something';
$login = $_POST['login'];
$passwd = $_POST['pass'];
$name = $_POST['name'];
$surname = $_POST['sur'];
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Error " . $conn->connect_error);
} else {
echo "Connect success <br>";
}
$check = "select login from users where login = '$login'";
$test = $conn->query($check);
if(mysqli_num_rows($test) = 0){
$sql = "insert into users
values (null,'$login','$passwd','$name','$surname')";
if ($conn->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error " . $sql . "<br>" . $conn->error;
}
} else {
echo "The login is already in use!";
}
$conn->close();
?>
I'm getting "Can't use function return value in write context" on line
if(mysqli_num_rows($test) = 0)
which checks if there are any records with that login.
I used something similar before and it worked perfectly so what could be the problem now?
Write this
if(mysqli_num_rows($test) == 0)
Instead of,
if(mysqli_num_rows($test) = 0)

PHP connetion to mysql server database

I just want to test db connection from my browser. But i get empty page. I am not getting Error message.
<?php
$con = mysqli_connect('http://ec2-54-67-69-153.us-west-1.compute.amazonaws.com/', 'root', 'root') or die(mysqli_error($con));
if ($con) {
echo "success";
} else {
echo "fail";
}
mysqli_close($con);
?>
**Here is a handy function that connects you to a Database, using *Object Oriented* style:**
function MySQLi_quickConnect()
{
$host = 'somewebsite.db.120327161.hostedresource.com'; //or 'http://localhost'
$username = '<YOUR USERNAME>';
$password = '<YOUR PASSWORD>';
$database = '<YOUR DATABASES NAME>';
$db = new MySQLi($host,$username,$password,$database);
$error_message = $db->connect_error;
if($error_message != NULL){die("Error:" . $error_message . "<br>" . "Occured in function
MySQLi_quickConnect");}
return $db;
}
**A simple example on how you would query the Database:**
$db = MySQLi_quickConnect(); //this is your new Database object
$sql = "<YOUR SQL STATEMENT>";
$stmt = $db->query($sql);
if(!$stmt){die('MyError : ('. $db->errno .') '. $db->error);} //kill script, show errors

Fetching a result from selection query in php function

I have a php function of selection from mySql database:
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
echo $qry;
$result = mysql_query($qry);
while ($Res_user = mysql_fetch_assoc($result) ) {
return $Res_user['tax_id'];
}
}
an error is shown Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 446 and the line is while ($Res_user = mysql_fetch_assoc($result)
So what is the problem ? How can i fix it?
Try this
function Master_file($name, $latin ){
$dsn = 'mysql:host=localhost;dbname=nom';
$username = 'utilisaeur';
$password = 'K3Pud1';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$result = $db->prepare("SELECT tax_id FROM master where name =:name");
$result->bindValue(':name', $name);
$result->execute();
foreach($result->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $Res_user['tax_id'] . '<br />';
}
}
EDIT
The function above has just been updated to use PDO, display any errors, and output the tax_id value to the browser
You may try this, since your returning here return $Res_user['tax_id']; so I think you need a single row instead
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
if (!$connect) {
die("Could not connect: " . mysql_error());
}
$db=mysql_select_db($NAME_DB, $connect);
if (!$db) {
die ("Can't use " . $NAME_DB . " : " . mysql_error());
}
$qry = "SELECT tax_id FROM master where name ='" . $name . "' and latin = '" . $latin . "'";
$result = mysql_query($qry);
if( $result ){
$row = mysql_fetch_assoc($result);
return $row['tax_id'];
}
}

PHP returning "undefined" variable to flash

I don't know what's wrong but the moment i've logged in, i wanted it to display hello + username that i log in with. But currently it only displays Helloundefined
This is my flash code:
var myurl2:String = "http://localhost:8888/storyboards/check_auth.php";
var scriptLoader2:URLLoader = new URLLoader();
var scriptRequest2:URLRequest = new URLRequest();
scriptRequest2.url = myurl2+"?ck=" + new Date().getTime();
scriptLoader2.addEventListener(Event.COMPLETE, handleLoadSuccess2);
scriptLoader2.addEventListener(IOErrorEvent.IO_ERROR, handleError2);
// turn off right click so that user cannot control the movie
stage.showDefaultContextMenu = false;
scriptRequest2.method = URLRequestMethod.POST;
scriptLoader2.load(scriptRequest2);
function handleLoadSuccess2(evt:Event):void
{
var variables2:URLVariables = new URLVariables( evt.target.data );
for (var prop in variables2) {
trace(prop+" is: "+variables2[prop]);
}
if (variables2.authenticated == "y") {
// if login details OK, load protected page
nextFrame();
display_txt.text ="Hello" + variables2.username;
} else {
// if login details OK, load protected page
var url:String = "http://localhost:8888/storyboards/login.html";
var request2:URLRequest = new URLRequest(url);
try {
navigateToURL(request2, '_self'); // second argument is target
} catch (e:Error) {
trace("Error occurred!");
}
}
}
function handleError2(evt:IOErrorEvent):void
{
}
stop();
//------------------and here's my php code for process_login.php----------------------//
<?php
$host = 'localhost';
$user = 'root';
$password = 'root';
// check correct variables have been received through the POST array
if (isset($_POST['username']) && isset($_POST['pwd'])){
session_start();
// base url
$baseURL = 'http://localhost:8888/storyboards/';
// include info for db connection
//require_once("connection.php");
// escape quotes
if (!get_magic_quotes_gpc()) {
foreach($_POST as $key => $value) {
$temp = addslashes($value);
$_POST[$key] = $temp;
}
}
// connect to mysql
$connection = mysql_connect($host, $user, $password) ;
if (!$connection) {
echo '&error=' . mysql_error() . '&';
die('Could not connect ' . mysql_error());
}
//echo 'Connected successfully.';
// connect to db
$database = 'registerform';
$db = mysql_select_db($database, $connection);
if (!$db) {
echo '&error=' . mysql_error() . '&';
die ('Not connected : ' . mysql_error());
}
//echo 'Selected successfully.';
// query
$query = 'SELECT user_name, pwd FROM users WHERE user_name = "' . $_POST['username'] . '" AND pwd = "' . sha1($_POST['pwd']) . '"';
$result = mysql_query($query, $connection);
if (!$result) {
echo '&error=' . mysql_error() . '&';
die ('Invalid query: ' . mysql_error());
}
// count the number of records
$numrows = mysql_num_rows($result);
if ($numrows > 0) {
$_SESSION['authenticated'] = $_POST['username'];
echo 'authenticated=y' . '&page=' .'pass.php&user_name='.$_SESSION['authenticated'];
} else {
echo 'authenticated=n&error=' . urlencode('Sorry, access denied.');
}
}
?>
//-----------and my php code for check_auth.php----//
<?php
// access to the current session
session_start();
$_SESSION['username'] = $_POST['username'];
// if session variable authenticated is not set
if (!isset($_SESSION['authenticated'])) {
echo 'authenticated=n';
} else {
echo 'authenticated=y';
}
?>
Is there anywhere in the above codes that I went wrong? Can someone out there pls help me :(

Categories