Why do I get "mysql_query(): supplied argument is not a valid" - php

Why do I get a "mysql_query(): supplied argument is not a valid" for the first...
$r = mysql_query($q, $connection);
In the following code...
$bId = trim($_POST['bId']);
$title = trim($_POST['title']);
$story = trim($_POST['story']);
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = {$bId}";
$r = mysql_query($q, $connection);
//confirm_query($r);
if (mysql_num_rows($r) == 1) {
$q = "UPDATE " . DB_NAME . ".`blog` SET
`title` = '{$title}',
`story` = '{$story}'
WHERE `id` = {$bId}";
$r = mysql_query($q, $connection);
if (mysql_affected_rows() == 1) {
//Successful
$data['success'] = true;
$date['errors'] = false;
$date['message'] = "You are the Greatest!";
} else {
//Fail
$data['success'] = false;
$data['error'] = true;
$date['message'] = "You can't do it fool!";
}
}
I also get an "mysql_num_rows(): supplied argument is not a valid MySQL result resource" error too.
Side notes: I am using 1&1 Hosting (worst hosting ever), custom .htaccess file with one line text to enable PHP 5.2 (only way with 1&1 Hosting).
Extra stuff add after the questions was posted...
Here is how $connection is defined. It is on its own page called connection.php that is called up using the require_once function. It it is called up on every page that require a database connection including the one in question...
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database Connection Failed: </br>" . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database Selection Failed: </br>" . mysql_error());
}
... I know it is working because this the same connect that I use for the page I have and I have no problems with it. I havent testing on my home server yet, but I am going to later to see if it is related to a 1&1 Hosting issue.
UPDATE: I am in the process of moving from 1&1 Hosting to HostMoster. 1&1 runs a PHP as CGI and runs PHP4 instead of PHP5 (you can make a custom .htaccess file to make it run PHP5). I will update you later.

The first would be because it's not a connection, and the second would be because it's not a query result because it wasn't a connection. Use mysql_error() to figure out what went wrong in the connection.

My guess is that $connection has not been properly opened. You should have a line like:
$connection = mysql_error($server, $user, $pass);
Also check mysql_error() to see the reason why it's failing.

I think that cletus meant to suggest that you need to have a mysql_connect() instead of mysql_error() before you attempt to perform a mysql_query(). It will probably look like this (with the exception that 1and1 may have given you a specific hostname to connect to for your database which you should use in place of localhost below):
//Make sure this goes before any of your other mysql_* functions
$connection = mysql_connect('localhost', 'yourUserName', 'yourPassword');
Passing $connection around for each of your queries isn't really necessary unless you have multiple database connections open concurrently that you are using and need to make sure to differentiate between the two when making query calls. Otherwise, mysql_query assumes that you are using the last database that you connected to.
Also, for security purposes as mentioned by Frank you should use mysql_real_escape_string() like so:
$q = "SELECT * ";
$q .= "FROM " . DB_NAME . ".`blog` ";
$q .= "WHERE `blog`.`id` = ".mysql_real_escape_string($bId).";

Tested on my local system (via WAMP), I had no problems. At the time when I had problems, I was using 1&1 Hosting. 1&1 Hosting run PHP as CGI, which probably cause my problems. I couldnt handle allof the crap with 1&1 and switch to HostMonster. Now, I don't any issues. Plus, I rather use cPanel over 1&1's admin panel.

Related

Query not executing. No errors

$query = "SELECT `ip` FROM `banned` WHERE `ip` = '$ip'";
$retval = mysqli_query($conn, $query);
if(!$retval){
die("Could not Execute Query: " . mysqli_error($conn));
} else {
if(mysqli_num_rows($retval) == 0){
echo "test";
} else {
header('Location: http://www.teutonic-development.net/index.php?p=banned');
}
}
when I'm running this code all that's printed out is: "Could not Execute Query:"
I really have absolutely no idea why it's doing this. I'm connecting fine in my init.php file. Which is where this file is.
My other script which just adds a log entry works fine. And if I run my $query in phpmyadmin's sql interpreter it runs perfectly fine (when I replace the $ip part with an actual ip of course)
Any suggestions?
Normally one would say that hey your query failed to execute story finish. But this case is interesting.
Your code is
die("Could not Execute Query: " . mysqli_error($conn));
and your error message is
Could not Execute Query:
Notice even though you have mysqli_error($conn) but there is no mysql error being shown. That confirms 100% that $conn is not properly established (contrary to what you think)
So take a look at your code again and see if $conn is really a mysqli resource and is available to your file in proper variable scope.

My php script is not using given username/pass/host rather using root#localhost (password: NO)

Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)

pg_query returns nothing

Newbie question about PostgreSQL. I'm migrating a MySQL/PHP app I've created, hosted on a Linux server, to PostgreSQL/PHP on a MacOSX Lion Server environment. It's my first experience with Postgres. The first query I'm testing doesn't work as it returns nothing (not even an error message, whichever check code I add). What did I do wrong? I've read articles on the web including the doc on php official website but all comments, personal methods and differences from version to version, either with Postgres or PHP, make it very confusing and I eventually don't understand exactly show I should write my query and fetch_array. Thanks for any suggestions.
Here is my code from the original MySQL application:
// below is the "connexion.php" file
function connexion ()
{
$link=#mysql_connect ("localhost","username","pwd");
if ($link && mysql_select_db ("database"))
return ($link);
return (FALSE);
}
// below is the "index.php" file
require ("connexion.php");
connexion() or exit();
$reqcount = mysql_query ("SELECT * FROM people");
$result = mysql_num_rows($reqcount);
echo "Total : ".$result." people";
mysql_free_result ($reqcount);
mysql_query("set names 'utf8'");
$reqcat = mysql_query ("SELECT catname FROM categories ORDER BY catname");
while ($fieldcat = mysql_fetch_array($reqcat))
{
$name = $fieldcat[catname];
echo $name."<br>";
}
mysql_free_result ($reqcat);
mysql_close ();
And here is the PostgreSQL adaptation:
// connexion.php
function connexion ()
{
$link=pg_connect("host=localhost port=5432 dbname=database user=username password=pwd connect_timeout=5 options='--client_encoding=UTF8'");
return ($link);
}
// index.php
require ("connexion.php");
$reqcount = pg_query ($link,"SELECT * FROM people");
$result = pg_num_rows($reqcount);
echo "Total : ".$result." people";
pg_free_result ($reqcount);
$reqcat = pg_query ($link,"SELECT catname FROM categories ORDER BY catname");
while ($fieldcat = pg_fetch_array($reqcat))
{
$name = $fieldcat[catname];
echo $name."<br>";
}
pg_free_result ($reqcat);
pg_close ();
The php code for postgresql doesn't call connexion() so it never connects, unlike the mysql code.
You can try your query if it fails display error
$reqcount = pg_query ($link,"SELECT catname FROM people") or die(pg_last_error());
This way you can see your error.
errors
UPDATE:
Remove the # in your connection to see the error, and add or die(pg_last_error())
to see the error

Transferred to new hosting/server - Now having issues with using MySQL for form validation

I'm having a lot of problems with the new hosting, but the more I look at it, it seems that they're all related to doing checks in my database when validating logins, registrations, and submissions. Here's an example of one.
I use jQuery to validate forms. One I use to determine if a username actually exists when a user is trying to log in (don't worry, I also check server side). On my development server, this works flawlessly. If you're not familiar with jQuery Validation, basically this returns a true or false back to the server in a form of some kind of JSON, but I'm not entirely knowledgeable on that part.
The code:
//Database Information vars (removed)
mysql_connect ($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$username = mysql_real_escape_string($login_username); // In validation, I can grab inputs like this.
$query = "SELECT username FROM registerusers WHERE username='$username';";
$res = mysql_query($query);
if (mysql_num_rows($res) > 0) {
$output = true;
} else {
$output = false;
}
echo json_encode($output);
The problem with this is that it always refers to the first clause and returns true, even if the username does not exist. For whatever reason, I think it's always returning 1 for mysql_num_rows($res).
This EXACT code (except for new database vars which I've checked a hundred times to be accurate) works as intended on my development server still. I can only assume that it has something to do with the new server, and that's why I'm asking Stack Overflow, because I have no clue.
The problem is that register_globals is enabled.
This poses a high security problem which is why it is disabled and deprecated.
Changing $login_username to $_GET['login_username']solves the problem.
Using the $_GET and $_POST super global arrays is not a security problem, but you should always sanitize your input (like you do with mysql_real_escape_string()).
Have you tried setting the MySQL connection to a variable, then calling the connection variable as the second parameter inside of the mysql_query? This has sometimes given me an issue on some servers, especially if they have certain debugging methods, errors, and warnings shut off by default:
//Database Information vars (removed)
$connect = mysql_connect ($dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$username = mysql_real_escape_string($login_username); // In validation, I can grab inputs like this.
$query = "SELECT `username` FROM `registerusers` WHERE `username` = '".$username."';";
$res = mysql_query($query, $connect);
if (mysql_num_rows($res) > 0) {
$output = true;
} else {
$output = false;
}
echo json_encode($output);
I've also changed the $query to a concatenated string with the variable, as some servers I have worked on sometimes are finicky in terms of putting variables inside of a string without delimiting them with "..".

Accesing XAMPP MySql Database from Another Computer

So a friend of mine and I are using both xampp on ubuntu, if that helps, to connect between each other's website, We both created the same php file to connect, so we use de IP of the other, but then it says an error
Warning: mysql_connect() [function.mysql-connect]: Host 'coke-laptop.local' is not allowed to connect to this MySQL server in /opt/lampp/htdocs/connection.php on line 2
Could not connect: Host 'coke-laptop.local' is not allowed to connect to this MySQL server
We have this code on the connection.php file:
<?php
$link = mysql_connect('10.100.161.37','root','');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db_selected = mysql_select_db('Prueba', $link);
if (!$db_selected) {
die ('Can\'t use Prueba : ' . mysql_error());
}
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT * FROM Agencia");
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['ID'] . " ";
echo $row['Nombre'] . "\n\r";
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
mysql_close($link);
?>
If we use the IP just like that, we can enter each others xampp normal welcome page.
Check you have enabled remote access to the MySQL server. Open the my.cnf file (probably found inside xampp/etc/), go to the [mysqld] section and add the following (using your own ip address instead of the example)
bind-address=192.168.1.100
If there is a line that says skip-networking, comment that out so it looks like this:
# skip-networking
then restart the MySQL server
It looks like your MySQL database isn't allowing you to connect remotely with the credentials you provided. You will need to configure a remote user to connect. Try looking into MySQL Grants.
For Example:
GRANT SELECT, INSERT ON database.* TO 'someuser'#'somehost';

Categories