How to fetch data? - php

This statement gives error
unable to fetch result from database
$res =$dbcon->exec("select *from tablename ");
$res->fetch();
Give an error.

change only one query
$res =$dbcon->exec("select *from tablename ");
to
$res =$dbcon->query("select *from tablename ");

You need a space in your query:
$res = $dbcon->exec("select * from tablename");
Depending on what $dbcon is, you may need to use the query method instead (part of alok.kumar's answer):
$res = $dbcon->query("select * from tablename");
Referenece: http://www.php.net/manual/en/pdo.query.php

Related

How do I count the number of rows in a MySQL Table?

I know that inside MySQL, you can use:
SELECT COUNT(*) FROM table
I have written the following code in PHP to display the number of rows on the page:
$sql = 'select * from users';
$data = $conn -> query($sql);
echo $data;
But when I run it, I get the following error:
Catchable fatal error: Object of class PDOStatement could not be converted to string in [Directory] on line 19.
I think the problem is that the returned value is not in string form. If that is correct, how would I be able to display the number of rows on the page?
If you want to count the rows you can do this with PDO:
$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);
Well, you arent badly off, you are almost there:
$sql = 'SELECT COUNT(*) as numrow FROM users';
$data = $conn -> query($sql);
rows = $data->fetchAll();
Depending on the type of return data, you could use
$rows->numrow if the return data is an object
There are some easy and faster way to do this
COUNT the column in query and fetch
$sql = "SELECT COUNT(id) AS total_row FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
echo $count['total_row'];
Using rowCount()
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;

how can i use two mysql query with user defined variable in php

select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
This query works in mysql console
but
$query = "
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
";
$result = mysql_query($query);
this code raise error in php
so, I tried this
$query="
select * from ct_product, (select #min_price:=min(prd_sale_price),#max_price:=max (prd_sale_price) from ct_product) as b
where prd_sale_price=#min_price or prd_sale_price=#max_price
";
$result = mysql_query($query);
that works
...
$query = "
select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product;
select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price;
";
$result = mysql_query($query);
What's the way that this code would work well without modification as my second way?
Use two calls to mysql_query:
$query1 = "select #min_price:=min(prd_sale_price),#max_price:=max(prd_sale_price) from ct_product";
$query2 = "select * from ct_product where prd_sale_price=#min_price or prd_sale_price=#max_price";
mysql_query($query1);
mysql_query($query2);
Variables are associated with a database connection, so they'll persist between the calls.
in PHP mysql_query() can handle only one query at a time
You can't make this method handle 2 query at the same time
what I can suggest is using mysql_query() for every query

Putting 2 WHERE statements together

I'm having problems putting two where statements together
My current code:
include 'config.php';
$result22 = mysql_query("SELECT * FROM messages WHERE to_user='".$_SESSION['username']."' AND to_read_yet='yes' ");
$num_rows22 = mysql_num_rows($result22);
echo "$num_rows22 ";
For some reason this isn't working. I am not getting any results i have checked the db and there are results which should come out
You should read about sql syntax. After where you put any number conditions with bool operators. Using 2 times where is incorrect
$result = mysql_query("SELECT * FROM messages WHERE to_user='".$_SESSION['username']."' AND to_read_yet='"no"' ");
Leave the second WHERE expression out, it's just WHERE condition_1 AND condition_2 AND condition_3 AND ....
$result = mysql_query("SELECT * FROM messages WHERE to_user='".$_SESSION['username']."' AND to_read_yet='"no"' ");
SELECT *
FROM messages
WHERE to_user = '".$_SESSION['username']."'
AND to_read_yet= '"no"'
try with:
$result = mysql_query("SELECT * FROM messages WHERE to_user='".$_SESSION['username']."' AND to_read_yet='no' ");
$result = mysql_query( "SELECT * FROM messages WHERE to_user='" . $_SESSION['username'] . "' AND to_read_yet='no'" );
Drop the second WHERE

Empty query result in php

I'm having troubles with a PHP code. The problems come when I execute a SQL query with a PHP variable inside it. The result doesn't shows anything, and the field in the database is not empty. Tried out with a static id (not variable) and the query works fine.
Do you know where I'm doing it wrong?
The query code:
$consultaVideoSeleccionado1 = mysql_query("SELECT * FROM videos WHERE idvideo = `'.$videoSeleccionado.'`;", $conexion);
Try this:
$consultaVideoSeleccionado1 = mysql_query("SELECT * FROM videos WHERE idvideo = `'.$videoSeleccionado.'`;", $conexion) or die(mysql_error());
That will give you an error message.
The problem is that you use both ` and ' as escape characters as the same time.
$consultaVideoSeleccionado1 = mysql_query("SELECT * FROM videos WHERE idvideo = '$videoSeleccionado';", $conexion);
should work.
Often things will be more clear when you echo the query so you can see the final result.
you are using double quotes on your query so there is no need for the dot . operator
$consultaVideoSeleccionado1 = mysql_query("SELECT * FROM videos WHERE idvideo = '$videoSeleccionado'", $conexion);
You are connecting string wrong! You are using ' single quote, but you should use double/none.
Try this query:
mysql_query("SELECT * FROM `videos` WHERE `idvideo` = '$videoSeleccionado';", $conexion)
Or
mysql_query("SELECT * FROM `videos` WHERE `idvideo` = '{$videoSeleccionado}';", $conexion)
Or
$q = "SELECT * FROM `videos` WHERE `idvideo` = '%s';";
mysql_query(sprintf($q, $videoSeleccionado), $conexion)
Edit:
If it's still not working problem can be in query, try checking if it is using mysql_error()(1) or try dumping query(2).
Example(1):
mysql_query("SELECT * FROM `videos` WHERE `idvideo` = '".$videoSeleccionado."';", $conexion) or die(mysql_error());
Example(2):
$q = "SELECT * FROM videos WHERE idvideo = '$videoSeleccionado';";
var_dump($q);
mysql_query($q, $conexion)

Select latest entry from MySQL database error

<?php
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("jmvarela_jacket") or die(mysql_error());
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
$row = mysql_fetch_array( $query );
echo $row['frase'];
?>
I cant get this to work.
I get this error:
Warning: mysql_fetch_array(): supplied
argument is not a valid MySQL result
resource in
/home/jmvarela/public_html/ihateyourjacket.com/latest/index.php
on line 7
I am trying to select the latest entry to the mysql database.
The table is called "quote"
There are three fields: id, frase and name.
Just to clarify (because this could be VERY bad coding) I am trying to get the "biggest" id and to display it's correspondant "frase".
you have not perform your query
$result = mysql_query($query);
$row = mysql_fetch_array( $result );
try this
Looks like you are not running the query.
// construct the query.
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
// run the query..THIS IS MISSING.
$result = mysql_query($query);
Also it's better to change SELECT * to SELECT frase, since you're interested only in the frase column. This will not bring all the unwanted columns from MySql to PHP, making your program perform better.
I´m not sure if this should be done but ill leave the complete running code for future refence.
<?php
mysql_connect("localhost", "user", "password") or die(mysql_error());
mysql_select_db("jmvarela_jacket") or die(mysql_error());
// construct the query.
$query = 'SELECT * FROM `quote` ORDER BY `id` DESC LIMIT 1';
$result = mysql_query($query);
$row = mysql_fetch_array( $result );
echo $row['frase'];
?>
Thanks to everyone!

Categories