PHP message "Error: No database selected", concernig this script - php

I have this script, but i don't know what could be wrong here when I hit "post" button on the main page. Where the error can come from?
The page script:
<?php
session_start();
include("dbconnection.php");
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$messages = clean($_POST['message']);
$user =clean($_POST['name']);
$pic =clean($_POST['name1']);
$poster =clean($_POST['poster']);
$sql="INSERT INTO message (messages, user, picture, date_created, poster)
VALUES
('$messages','$user','$pic','".strtotime(date("Y-m-d H:i:s"))."','$poster')";
mysql_query("UPDATE messages SET picture = '$pic' WHERE FirstName='$user'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header("location: lol.php");
exit();
$name=$_POST['name'];
$pic=$_POST['name1'];
mysql_query("UPDATE messages SET picture = '$pic' WHERE FirstName='$name'");
?>
This is the dbconnect file:
$con = mysql_connect("hostname","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("asl", $con);
?>

Ensure you have selected your db using mysql_select_db
mysql_connect('hostname','username','password') or die("not able to connect");
mysql_select_db('myDatabase');
And mysql_ extensions are deprecated.. Dont use it

this errors seems to be caused by either selecting wrong database or not selecting it.
check dbconnection.php and for this line in it
mysql_select_db("your_database_name",$your_connection);
See whether this line is present and pointing to database or not and make sure this databse exists
Update It seems that your file is not being included try require() so that it produces fatal error and you can see file s being including or not
require("dbconnection.php"); // will produce fatal errors

First of all mysql_connect is outdated and unsecure, better use PDO instead
<?php
session_start();
include("dbconnection.php");
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$messages = clean($_POST['message']);
$user =clean($_POST['name']);
$pic =clean($_POST['name1']);
$poster =clean($_POST['poster']);
$sql = $db->prepare("INSERT INTO message (messages, user, picture, date_created, poster) VALUES (:messages, :user, :picture, :date_created, :poster)");
$sql->bindParam(':messages', $messages);
$sql->bindParam(':user', $user);
$sql->bindParam(':picture', $pic);
$sql->bindParam(':date_created', strtotime(date("Y-m-d H:i:s")));
$sql->bindParam(':poster', $poster);
$stmt = $db->prepare("UPDATE messages SET picture = :picture WHERE FirstName = :user");
$stmt->bindParam(':picture', $pic);
$stmt->bindParam(':user', $user);
$stmt->execute();
if (!$sql->execute())
{
die('Error: ' . mysql_error());
}
$name=$_POST['name'];
$pic=$_POST['name1'];
$stmt_2 = $db->prepare("UPDATE messages SET picture = :picture WHERE FirstName = :name");
$stmt_2->bindParam(':picture', $pic);
$stmt_2->bindParam(':name', $name);
$stmt_2->execute();
header("location: lol.php");
?>
This is the dbconnect file:
<?php
//Connect to sql db
try {
$user_db = "username";
$pass_db = "password";
$db = new PDO('mysql:host=localhost;dbname=asl', $user_db, $pass_db);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>

Related

Having trouble creating a safe way for users to update their data

I am making a way for users to edit their data. My first way I did it worked, but then I remembered that it is very insecure and that I should never insert data directly into the database; at least that's what I was told. I try to make it more secure by doing the VALUES (?,?,?,?,?) thing so that the data is not directly going in, which seemed to work fine in my registration page (which I can include if you want).
To start, here is my original update data page that worked fine but it does not use the (?,?,?,?,?) method:
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
Here is what I tried to do to make it more secure but this doesn't seem to work. Specifically the $query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'"; seems to be the issue, though the syntax looks fine to me
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
So I am not sure what the problem is. In my experience with PHP, the syntax should be fine but I must be missing something.
It's quite simple actually, you went from
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
TO
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
It appears you confused an INSERT statement vs. an UPDATE statement when rewriting so to fix you simply use your old statement with the new style...
$query = "UPDATE usertable SET SkypeID = ?, Email = ?, Region = ?, CRank = ?, DRank = ? WHERE UserID = $userid";

Call to a member function execute() on a non-object in

I have the following error, and this is the exact same form processing file I use for registering a user, but I changed it for the appropriate table and columns. While the reg works fine every time.
Here is the code where the error is located:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
Here is the full code:
<?php
$servername = "localhost";
$username = "root";
$password = "Af2vaz93j68";
$dbname = "pdo_ret";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$eventname = $_POST['eventname'];
$about = $_POST['about'];
$website = $_POST['website'];
if($eventname == '') {
$errmsg_arr[] = 'You must enter your Email';
$errflag = true;
}
if($about == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
if($website == '') {
$errmsg_arr[] = 'You must enter First Name';
$errflag = true;
}
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Youre confusing PDO and mysqli. mysqli does not support named parameters so you stmt is not compiling and Mysqli::prepare is returning false. Additionally mysqli does not support passing the param to be bound through mysqli_stmt::execute so even if you switch to positional placeholders your execute will fail.
This is what you would need for mysqli:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
// check to make sure the statement was prepared without error
if ($stmt) {
// the statement is good - proceed
$stmt->bind_param('sss', $eventname, $about, $website);
$stmt->execute();
}
Additionally this makes no sense at all:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will just run the same query again either inserting a second row of the exact same data, or perhaps creating a duplicate key error depending upon your schema.
If you want to test that the previous query succeeded you would do something like:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param('sss', $eventname, $about, $website);
$success = $stmt->execute();
} else {
$success = false;
}
if ($success === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
If you want to use PDO (which i prefer and usually recommend) your code would look something like this:
$conn = PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $sql . "<br>" . $e->getMessage();
}

Inserting user updates into SQL with PHP

I think I am really close now - there are no more nasty Orange boxes with errors in - the only problem I can see at the moment is that once I update the table (after the
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')";
) I get the message "No rows updated" echo to the screen!
Any ideas what the problem is?
Thanks.
<?php
//Start session
session_start();
$_SESSION['SESS_LOGIN'];
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$employ = clean($_POST['employer']);
$address = clean($_POST['flat']);
?>
<?Php
//Insert employer and address into database row for logged in user.
$login_name = $_POST['login_name'] ;
$qry = "UPDATE 'members' ('employer', 'flat') WHERE login='$login_name' VALUES ". " ('$employ', $address')" ;
$result = #mysql_query($link, $qry);
//Check whether the query was successful or not
if(!$result) {
echo "No rows updated";
exit();
}else {
echo "Success";
}
?>
Don't use VALUES, use SET:
"UPDATE `members` SET `employer` = '".$employ."', `flat` = '".$address."' WHERE `login`='".$login_name."'"
First of all you should not suppress error messages by using the # opperator if you are looking for issues in your code. Also you are using the wrong parentheses (' instead of `). The rest of your code looks fine. maybe you need to give us some info about the database structure otherwise

PHP mysql_real_escape_string(); whats the correct method using mysqli?

its a little difficult to explain. I've build the mysql function which works fine and with the depreciation of mysql I will need to change this function to use mysqli rather than the mysql method.
I current have:
$con = mysql_connect("host", "username", "pass");
mysql_select_db("db", $con);
$Username = mysql_real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$Query = mysql_query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'") or die(mysql_error());
$Query_Res = mysql_fetch_array($Query, MYSQL_NUM);
if($Query_Res[0] === '1')
{
//add session
header('Location: newpage.php');
}
else {
echo 'failed login';
}
Now I've applied mysqli to this and it's not returning any data or errors but the function still complies.
$log = new mysqli("host", "user", "pass");
$log->select_db("db");
$Username = $log->real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$qu = $log->query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'");
$res = $qu->fetch_array();
if($res[0] === '1'){
//add session
header('Location: newpage.php');
}
else {
$Error = 'Failed login';
sleep(0.5);
}
echo $res['username'].' hello';
}
But I'm unsure on why this is wrong. I know it's probably a simply answer
Just to have it as an answer:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
e.g.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
You may check if the connection is establishing before using real_escape_string()
if ($log->connect_errno) {
echo "Failed to connect to MySQL: (".$log->connect_errno.")".$log->connect_error;
}
afaik, there's no problem with $log->real_escape_string($_POST['user']);

Do Not Duplicate VALUE if already exist on MySQL

I've been trying to accomplish this, but as other issues I just can't figured it out. I've been reading around for posibles solutions but non of them goes along with my code, or if they do I can't figure out how or where to use them.
I have a DB where a user sends records. The database consist in few tables containing the Following "Name, Lastname, Phone". If any of this values is duplicate, I would like my code to identify and Ignore the submission of the Form if ALL this VALUES already exist on the DB.
Here is my code:
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$_POST[Name]','$_POST[LastName]','$_POST[Phone]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
mysql_close($con);
?>
The mysql_* function are all deprecated now, and should NEVER be used. change your code to do something like the following:
//Set up a PDO connection to MySQL
$host = 'host_name';
$dbname = 'database_name';
$user = 'user_name';
$pass = 'user_pass';
try
{
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
//Determine whether the appropriate values have been passed.
if(isset($_POST['Name']))
{
$name = $_POST['Name'];
}
else
{
echo "You must provide a name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['LastName']))
{
$name = $_POST['LastName'];
}
else
{
echo "You must provide a last name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['Phone']))
{
$name = $_POST['Phone'];
}
else
{
echo "You must provide a phone number!";
exit; //This may not be what you want to do here, it's an example action
}
//Set up the query using anonymous values
$sql="INSERT INTO people (Name, LastName, Phone) VALUES ('?','?','?')";
$sth = $DB->prepare($sql);
try
{
//Attempt to execute the insert statement
$sth->execute(array($_POST[Name], $_POST[LastName], $_POST[Phone]));
echo "Record Added";
}
catch(PDOException $e)
{
//If the insert failed, then you can handle the error, and determine
//what further steps need to be taken.
echo "Record Not Added";
}
Here's another question with a similar setting, that may also be useful to you:
https://stackoverflow.com/a/10414922/1507210
search in the table before insert
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$name = mysql_real_escape_string($_POST[Name]);
$LastName= mysql_real_escape_string($_POST[LastName]);
$Phone= mysql_real_escape_string($_POST[Phone]);
$search_res=mysql_query("SELECT * from people where Name='$Name' OR LastName='$LastName' OR Phone='$Phone'");
if(mysql_num_rows($search_res) < 1){
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$Name','$LastName','$Phone')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
}else{
echo "User Already exits";
}
mysql_close($con);
?>
Try this easy solution
$result = mysql_query("SELECT * FROM TABLE WHERE Column = 'value' ");
if( mysql_num_rows($result) < 1) {
mysql_query("INSERT INTO table (column) VALUES ('value') ");
}

Categories