A valid SQL-command won't run in PHP - php

I ran the following code in PHPAdmin's terminal:
SELECT COUNT( * )
FROM User
WHERE email = 'ijp'
and got result 0.
Then part of my PHP program goes as follows:
$email = clean_input($_POST['email']);
$query = "SELECT COUNT(*) FROM user WHERE '.$email.'=email";
echo $query;
$result = mysqli_query($link, $query);
echo $result;
mysqli_close($link);
I have checked that I logging into the database went fine. Still the output is
SELECT COUNT(*) FROM User WHERE email='ijp'
Catchable fatal error: Object of class mysqli_result could not be converted to string in .../html/register.php on line 49
How can I run MySQL-commands in PHP?

You are passing the $result resource to echo which expects a string. You need to use one of the mysqli_fetch_* functions to read the value from the $result and then print it.
mysqli_fetch() is deprecated, use mysqli_fetch_array or mysql_fetch_assoc or mysql_fetch_all, for example:
$row = mysqli_fetch_array($result);
if($row) {
echo $row[0];
}

Try using
$query = "SELECT COUNT(*) FROM user WHERE email=\"".$email."\"";

If the value or $email is 'ijp', the value of $query after
$query = "SELECT COUNT(*) FROM user WHERE '.$email.'=email";
Would be...
SELECT COUNT(*) FROM user WHERE ijp=email
Use '$email' instead of '.$email.'

all the above answers are all correct but one thing was ommited... you need to differentiate between a table called "User" and one called "user" - they are case-sensitive on *NIX systems (Linux and the like)

Related

Check value in MySQL from PHP

I am fairly new to PHP.
What I want is not much. I just want to place a check on my page which goes to database and check for value 1 or 0. 1 means "enable" so page continues ; and 0 means "disable" and page dies.
someone suggested the following but it didn't work
$sql = mysql_query("SELECT * FROM members WHERE access= '1'");
$user = mysql_query($sql);
echo $user;
if ($user !=="1") {
echo "You are not the proper user type to view this page";
die();
}
Thank you so much for your time.
Firstly, you're using mysql_query() twice and that alone will cause a syntax error.
You're also not looping over results, so use the following to achieve what you want to do.
$sql = "SELECT * FROM members WHERE access= '1'";
$user = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($user)){
if ($row['access'] !=="1") {
echo "You are not the proper user type to view this page";
die();
}
else {
echo "You are the right type.";
}
}
If your query requires a db connection to the query, you will need to do:
$user = mysql_query($sql, $connection);
This assuming a mysql_ successful connection. However, that API is deprecated as of PHP 5.5 and deleted as of PHP 7.0 and note that different MySQL APIs do not intermix.
It's time to step into the 21st century and use either the MySQLi_ or PDO API.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
You may also have to select an actual row (or rows) instead of SELECT * FROM members
I.e.:
SELECT column_1, column_2 FROM members
Consult these following links http://php.net/manual/en/function.mysql-error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
You can also achieve this with mysql_num_rows():
$result = mysql_query("SELECT * FROM members WHERE access= '1'");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}
You might also want to add to the WHERE clause:
$result = mysql_query("SELECT * FROM members WHERE access= '1' AND column='x' ");

Error message when using COUNT(*) [duplicate]

This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 1 year ago.
I'm currently receiving this error message:
"Catchable fatal error: Object of class mysqli_result could not be
converted to string in ".
I'm trying to count the number of rows in a table. I know you can also use mysqli_num_rows but I thought I could just use SELECT COUNT ( * ) FROM table but it doesn't seem to be working. How can I get the Count(*) to work?
My code:
$query = "SELECT COUNT(*) FROM category";
$select_all_categories = mysqli_query($connection, $query);
echo "<div class='huge'> $select_all_categories </div>"
This won't work because mysqli_query returns an object filled with data, data that needs to be fetched by either mysqli_fetch_array or mysqli_fetch_assoc.
If you desire to get the count, you would need to do this instead:
$query = "SELECT COUNT(*) as count FROM category";
$select_all_categories = mysqli_query($connection, $query);
$data = mysqli_fetch_assoc($select_all_categories);
echo "<div class='huge'> " . $data['count']. " </div>"
$select_all_categories is an object, it is not a simple string. Therefor, you cannot use echo with it.
You will need to get the actual results before you can even get to the point of being a viable string.
In your case, for a simple count:
$query = "SELECT COUNT(*) AS 'count' FROM category";
$select_all_categories = mysqli_query($connection, $query);
$rows = $select_all_categories->fetch_assoc();
$string = $rows[0]['count'];
echo "<div class='huge'> $string </div>"
Notice that I gave the column the alias of count in the MySQL Query.
Your query (including COUNT(*)) is fine, it is not generating the error here. The error you're getting is a PHP Error - the script itself has issues. PHP is telling you that you can't echo an object. You can only echo strings, though PHP will convert most data types to strings for you (like integers for example) if you try to echo them.
$select_all_categories variable it's a object, you can read about it in documentation. You can use with that methods fetch_all, fetch_assoc, fetch_row, etc.
In your case I recommend use fetch_row, example:
<?php
$connection = new mysqli('127.0.0.1', 'root', 'www', 'ccc');
$select_all_categories = $connection->query('SELECT COUNT(*) FROM `category`');
var_dump($select_all_categories->fetch_row()); // fetch_row() will return "1" for my database

How to set a variable in where clause of Select query in php

while executing the below query i'm not getting sucess value
$name=qwe;
$result = mysql_query("SELECT *FROM USER WHERE name = $name");
Instead of above query if i put the below, I can able to get the appropriate ans:
$result = mysql_query("SELECT *FROM USER WHERE name = 'qwe'");
Can anyone give a solution for my first query??
Close the variable in quote and concatenate the string into query
$name= "qwe";
$result = mysql_query("SELECT *FROM USER WHERE name = '".$name."'");
one more note
please use mysqli for security purposes. Thanks
Use the following:
$result = mysql_query("SELECT *FROM USER WHERE name = '".$name."'");
P.S. I have not tested the above code but it should work.
select * from table_name where col_name = '".$variable."'
Directly use :
$name = 'qwe';
$result = mysql_query("SELECT * FROM USER WHERE name = '$name'");
And on more advise, you should never use mysql_* functions now as they have been deprecated in newer versions of PHP and will produce the notices.

php functions within functions

ihave created a simple project to help me get to grips with php and mysql, but have run into a minor issue, i have a working solution but would like to understand why i cannot run this code successfully this way, ill explain:
i have a function,
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
this fetches all the movies in my db, then i wish to get the count of actors for each film, so i pass in the get_actors($id) function which gets the movie id and then gives me the count of how many actors are realted to a film.
here is the function for that:
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
the functions both work perfect when called separately, i just would like to understand when i pass the function inside a function i get this warning:
Warning: mysqli_fetch_array() expects
parameter 1 to be mysqli_result,
boolean given in
/Applications/MAMP/htdocs/movie_db/includes/functions.inc.php
on line 287
could anyone help me understand why?
many thanks.
mysqli_query failed to run your query:
Returns FALSE on failure. For
successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will
return a result object. For other
successful queries mysqli_query() will
return TRUE.
Before running mysqli_fetch_array test $result... Something like:
if ($result !== false)
$row = mysqli_fetch_array($result);
else
return false;
Seems like a variable scope issue within your SQL statement. Outputting the SQL should show you the "true" error.
You may want to try using classes with your functions, for example:
class getInfo {
function fetch_all_movies(){
global $connection;
$query = 'select distinct * FROM `'.TABLE_MOVIE.'` ORDER BY movieName ASC';
$stmt = mysqli_prepare($connection,$query);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt,$id,$name,$genre,$date,$year);
while(mysqli_stmt_fetch($stmt)){
$editUrl = "index.php?a=editMovie&movieId=".$id."";
$delUrl = "index.php?a=delMovie&movieId=".$id."";
echo "<tr><td>".$id."</td><td>".$name."</td><td>".$date."</td><td>".get_actors($id)."</td><td>Edit | Delete</td></tr>";
}
}
function get_actors($movieId){
global $connection;
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_array($result);
return $row[0];
}
}
$showInfo = new getInfo;
//fetch all movies
$showInfo->fetch_all_movies();
//List actors from movie 1
$showInfo->get_actors("1");
In case of an error mysqli_query will return false. You have to handle the error a simple way to do this might be:
$result = mysqli_query($connection,$query);
if (!$result) {
die(mysqli_error($connection));
}
$row = mysqli_fetch_array($result);
Please note that terminating (by doing die() ) usually is no good way to react on an error, log it, give the user anice error page etc. It's alsonogood practice to give the low level error message toauser, this might motivate users to try to exploit a possile security issue.
Last remark: you were writing
$query = 'SELECT DISTINCT COUNT(*) FROM `'.TABLE_ACTORS.'` WHERE movieId = "'.$movieId.'"';
you should properly escape the movieId there.

MySQL PHP count(*) returning something weird

I'm running the following query, expecting it to return an INTEGER, but it returns "Resource id #3"
What am I doing wrong?
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
echo $queryPlans;
There are actually 15 rows in this table, and I would like to return the number 15.
Any suggestions?
mysql_query will return a php resource(see: http://www.php.net/manual/en/language.types.resource.php).
The returned resource should then be passed to mysql_fetch_assoc or similar.
Since you are only getting the count, you can use the following:
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
$count = mysql_result($queryPlans,0,0);
echo $count;
You need:
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
$row = mysql_fetch_array($queryPlans);
echo $row[0];
mysql_query() isn't returning the result. It's returning a resource you can loop across and interrogate for rows (as above).
This is actually expected behavior according to the documentation:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
It's a regular select that returns one row with one column and should be treated as such. You can call mysql_fetch_array on the result:
$row = mysql_fetch_array($resource);
$count = $row[0];
mysql_query() returns a result resource. You need another function the get "valuable information" from that resource. In this case mysql_fetch_array()/mysql_fetch_row()/mysql_fetch_object as cletus pointed out. Or (since it's only a single value) mysql_result().
Any sql query may fail for various reasons. You should always check the return value of mysql_query(). If it's FALSE something went wrong and mysql_error() can tell you more about it.
$mysql = mysql_connect(...) or die(mysql_error());
mysql_selecT_db(.., $mysql) or die(mysql_error($mysql));
$query = "SELECT count(*) FROM infostash.rooms";
$queryPlans = mysql_query($query, $mysql) or die(mysql_error($mysql));
$cRows = mysql_result($queryPlans, 0);
echo $cRows;
If you are planning on using the full query later (e.g. select , rather than count()), you can save yourself a database hit by using mysql_num_rows() on the full query. Example:
$queryPlans = mysql_query("SELECT * FROM infostash.rooms");
$results = mysql_fetch_array($queryPlans);
echo "There were " . mysql_num_rows($queryPlans) . " results";
while($row = mysql_fetch_assoc($queryPlans)){
// Do stuff here
}
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
mysql_num_rows($queryPlans);
http://us.php.net/manual/en/function.mysql-num-rows.php

Categories