Include no database selected - php

I have a project (exisiting) and I am ordered to continue it
but there's something strange
in my connection
<?php
include "adodb5/adodb.inc.php";
$config['mysqlhost'] = 'localhost';
$config['mysqluser'] = 'xxx';
$config['mysqlpass'] = 'yyy';
$config['mysqldb'] = 'zzz';
$DB = ADONewConnection('mysql');
$DB->Connect($config['mysqlhost'],$config['mysqluser'],$config['mysqlpass'],$config['mysqldb'],true);
?>
and if I try to call query (same queries as below) from this page, it works (and when I echo, it shows the value)
So I go to other page
<?
include ("inc/con.php");
?>
<?php
$sql = ("SELECT * FROM table");
$query = mysql_query($sql)or die($myQuery."<br/><br/>".mysql_error());
$result = mysql_fetch_array($query);
echo $result ['table id'];
?>
and the result is
Notice: Undefined variable: myQuery in C:\xampp\htdocs\d88\www\mypage.php on line 9
No database selected
is there anything wrong with it?
since i try on con page, it works and when i include it to other page, it not working

You are not defining any $myQuery either in inc/con.php nor in the same file itself. Also you are not selecting any database with mysql_select_db:
mysql_select_db($config['mysqldb']);
You are suggest, also, not to use mysql_* functions as they are going to be deleted and are yet deprecated (and you can use PDO or mysqli).
Notice: I think $sql = ("SELECT * FROM table") gets evaluated as $sql = true.

You can not connect with ADODB connection and establish a query with mysql_query.
the syntax is something like this mysql_query ($query ,$con). $con is optional but if you do not specify it, the last link opened by mysql_connect() is assumed; but you have not any mysql_connect() statement before

because of my version of php, i must use <?php ?> instead of <? ?>
thanks for helping

Related

Variables from included php file

I currently have a php file with html code in it. At the beginning of the body tag im including a dbcon.php which contains a db connection, a query and a fetch_result. I now want to use those results later in the html file but i cant get it to work.
Website-file looks like this:
<html>
<head>...</head>
<body>
<?php include("dbcon.php"); ?>
...
<some html stuff>
...
<? here i want to use the data from the query ?>
...
</body></html>
The dbcon.php simply contains the connection, the query and the fetch_results.
edit:
dbcon:
<?php
$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query($con,"SELECT * FROM table");
$results = mysql_fetch_array($results_query);
?>
I cant access the data in the lower part of the html file.
Your code is "right", in that you don't need anything more to access your dbcon.php variables.
But you're mixing mysql_ and mysqli_ syntax :
mysql_query take as first parameter the query, not the connexion
mysqli_query take as first parameter the connexion, and the query as second one
You should use mysqli_ :
$con = mysqli_connect("localhost:8889","user","pw","db");
$result_query = mysqli_query($con, "SELECT * FROM table");
$results = mysqli_fetch_array($results_query);
Another version, object oriented :
$mysqli = new mysqli("localhost:8889", "user", "pw", "db");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$results = array();
if ($result_query = $mysqli->query("SELECT * FROM table")) {
$results = $result_query->fetch_array();
}
don't use mysql_ function,it is depricated.
anyway you use wrong variable name. $results_query in mysql_fetch_array($results_query) so change it to $result_query and it might work.
<?php
$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query("SELECT * FROM table");
$results = mysql_fetch_array($result_query );
?>

PHP mysql query syntax errors

I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.

Where clause php is not working

this is my 1st php on the 1st place. if there is anything wrong with i did please help me with code. since i just started learning. i tried with so many tutorials but i was unable to undestand what im doing wrong.
<?php
include "db_config.php";
$query = mysql_query("SELECT * FROM places WHERE place_id ='".mysql_real_escape_string($_REQUEST[place_id])."'");
while($e=mysql_fetch_assoc($query))
$output[]=$e;
echo $row['name'];
mysql_close();
?>
Is this correct?
im not sure how it is working.
$stmt = $db->prepare("SELECT * FROM table WHERE $_REQUEST[place_id]");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
You have a typo on this line:
while($e=mysql_fetch_assoc($q))
$q needs to be $query. I do not see a variable $q in your code. This is a common problem in php code as if you introduce a name like $q php is "nice" enough to create the variable for you and initialize it to null instead of sanely giving you an error.
You need to privode mysql_fetch_assoc() with the results of mysql_query, here $query.
<?php
include "db_config.php";
$query = mysql_query("SELECT * FROM places WHERE place_id='".mysql_real_escape_string($_POST[place_id])."'");
while($e=mysql_fetch_assoc($query))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
Moreover, you need to use some pdo or mysqli since mysql_ are deprecated: http://php.net/manual/en/function.mysql-query.php

mysql_real_escape_string() expects parameter 1 to be string

require("includes/connect.php");
$result = mysql_query("SELECT * FROM entries", $link);
while ($row = mysql_fetch_array($result)) {
htmlentities($row['quotes']);
}
I am trying to display data that is in the database, but I keep on getting:
Warning: mysql_real_escape_string() expects parameter 1 to be string
Is there anything wrong in the above code that is causing the problem? I am quite new to PHP and I am trying to understand what's going on and why it's doing it.
connect.php
$link = mysql_connect("localhost", "root", "");
if (!$link) {
die("Could not connect to the db");
}
mysql_select_db("ENTRIES", $link);
(I'm working on this locally, so user/pass really isn't important right now)
I don't see the point with escaping the above query, but you could do it like this:
$result = mysql_query(mysql_real_escape_string("SELECT * FROM entries"), $link);
You should read the documentation: mysql_real_escape_string()
As the error explains mysql_real_escape_string() takes a string as a parameter. In your code you posted as a comment you are passing $link which isn't a string, it's a database connection.
As #kristen, has said to solution should be to wrap you sql statement like so
$result = mysql_query(mysql_real_escape_string("SELECT * FROM entries"), $link);
If you are still receiving the error after this, you must be using the function elsewhere.

PHP will not delete from MySQL

For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!

Categories