I have the following PHP code:
$sql = new mysqli(/*connection info/db*/);
$query = $sql->$query("SELECT * from users WHERE /* rest of code */);
I was now wondering if there was any way I could retrieve the amount of rows that the above query found...
You should consider using PDO, it's safer and a more object oriented approach:
$database = new PDO(/*connection info/db*/);
$statement = $database->prepare('SELECT FROM fruit WHERE fruit_id = ? AND name = ?');
$statement->bindValue( 1, 'fruit_id_value' );
$statement->bindValue( 2, 'Banana' );
$statement->execute();
$count = $statement->rowCount(); # <-- The row count you are looking for!
--> visit http://php.net/manual/en/pdostatement.rowcount.php for more info
in Mysqli I know you can do
printf("Number of rows: %d.\n", $sql->num_rows);
Here is all the code
<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
printf("Number of rows: %d.\n", $stmt->num_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
I got that from this php manual http://php.net/manual/en/mysqli-stmt.num-rows.php
There is a modifier for the SELECT query that holds on to the information of the count you need: SQL_CALC_FOUND_ROWS
SELECT SQL_CALC_FOUND_ROWS * from users WHERE /* rest of code */
After running that query, you can run SELECT FOUND_ROWS(); to get the resulting number of rows.
If all you need is the count, you can just do
SELECT count(*) from users WHERE /* rest of code */
Related
I'm trying to make the below code have an if/else statement in the while section? I'm trying to do something like, if the result is the last row in the mysql table then display the first row in the table. Otherwise display the id row from the $id_related variable.
My goal is to create a 'next' button that esentially loops through the database table - going from id 1 to 10 and when the user gets to 10 and pushes 'next' button, it goes back to id 1.
require('connect.php');
$id_related = mysqli_real_escape_string($db, $_GET['id']);
$sql_related = <<<SQL
SELECT *
FROM `article_img`
WHERE `id` > '$id_related' ORDER BY id LIMIT 1
SQL;
if(!$result = $db->query($sql_related)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo '
<a href="article.php?id='.$row['id'].'&size='.$row['size'].'">
<div style="background-image: url('.$row['img'].');">
</div>
</a>
';
}
Note:
You can check the number of rows your query will return. If the current $_GET['id'], for example is 10 then binds on your query, and it returns 0, go back to the first id row of your table. So you don't have to worry updating your code in the future if you want to extend the rows of your table.
You should use mysqli_* rather than the deprecated mysql_* API.
Your code for connect.php:
$con = new mysqli("YourHost", "Username", "Password", "Database"); /* REPLACE NECESSARY DATA */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
And your main code:
require('connect.php'); /* YOUR CONNECTION */
if($stmt = $con->prepare("SELECT id,size,img FROM article_img WHERE id > ? ORDER BY id LIMIT 1")){
$stmt->bind_param("i",$_GET["id"]); /* BIND THIS VARIABLE TO YOUR QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->store_result(); /* NECESSARY WHEN GETTING THE NUMBER OF ROWS */
$noofrows = $stmt->num_rows; /* GET NUMBER OF ROWS */
if($noofrows == 0){ /* IF FOUND NO ROW GREATER THAN CURRENT CODE */
/* GET THE FIRST ROW IN YOUR article_img */
$stmt2 = $con->prepare("SELECT id,size,img FROM article_img ORDER BY id LIMIT 1")){
$stmt2->execute();
$stmt2->store_result();
$stmt2->bind_result($id,$size,$img);
$stmt2->fetch();
$stmt2->close();
} /* END OF SECOND PREPARED STATEMENT */
} /* END OF IF $noofrows IS 0 */
else { /* IF THERE IS A VALID NEXT ROW */
/* GET THE NEXT PAGE */
$stmt->bind_result($id,$size,$img); /* BIND THE RESULT TO THESE VARIABLES OF THE FIRST QUERY */
$stmt->fetch(); /* FETCH THE RESULT */
} /* END OF ELSE */
$stmt->close();
} /* END OF PREPARED STATEMENT */
echo '<a href="article.php?id='.$id.'&size='.$size.'">
<div style="background-image: url('.$img.');">
</div>
</a>'; /* YOUR LINK TO NEXT PAGE */
I am very new to MySQl and I'm trying to check if an inputed email matches with any from my table. If it matches, I need to put the email and the other columns of the same row in another table.
What I get now is a blank row added to table2.
<?php
include "config.php";
$email = $_POST['email'];
$match = mysqli_query("SELECT email FROM table1 WHERE email = $email");
if($conn->query($match)){
//here i have to find the name, school, and grad_year that matches
// with the email from table 1 which is in the same row. I tried a couple of
//things but it didn't work. So i don't know what to put in there.
$insert = "INSERT INTO table2 VALUES(name,'$email',school,grad year )";
$conn->query($insert);
}
?>
Any help would be much appreciated!
Don't ever use the mysql* functions. They are deprecated and insecure. Use mysqli* or PDO instead. See below for sample code (I have NOT run it and there may be errors - the idea is to get you on the right road...)
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$email = $_POST['email'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE email=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $email);
/* execute query */
$stmt->execute();
/* bind result variables */
# NOTE: You may prefer $stmt->get_results() and $result->fetch_assoc()
# to this $stmt->bind_result() and $stmt->fetch().
$stmt->bind_result($name, $junk, $school, $grad_year);
/* fetch value */
if ($stmt->fetch()) {
$stmt2 = $mysqli->prepare("INSERT INTO table2 VALUES (?,?,?,?)");
$stmt2->bind_param("ssss", $name, $email, $school, $grad_year);
$stmt2->execute();
$stmt2->close();
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Or, if you don't care to know details along the way, this is a lot faster and simpler:
// yada,yada - get a conx
$email = $_POST['email'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO table2 SELECT * FROM table1 WHERE email=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $email);
/* execute query */
$stmt->execute();
/* the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function */
}
(SOURCE: Example copied from http://php.net/manual/en/mysqli.prepare.php and modified)
I just want to count the number of rows in a table that already created in a database using php. I used mysqli(). I need the number of rows in the table as the output.
<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT count(*) cc FROM tablename")) {
/* fetch the first row as result */
$row = $result->fetch_assoc();
printf("Result set has %d rows.\n", $row['cc']);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
In fact it's a common question you can find the answer anywhere.
Like, http://php.net/manual/en/mysqli-result.num-rows.php
You could separate this problem in to two
I wanna know how to connect to mysql.
I wanna know how to write that sql instruction.
<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT columnName from tablename")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
EDIT:
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Try simple query like:
SELECT COUNT(*) AS count
FROM mytable
If you dont want to use COUNT in SQL, you can just select all rows (SELECT id FROM table) and then just use PHP count().
also you simply do this
"SELECT COUNT(*) AS `Rows`, `any column` FROM `tablename` GROUP BY `any column` ORDER BY `any column` "
mysqli_num_rows should do the trick if you want to count the rows in php.
I have a table named 'transactions', in which i store a user's all transactions. i want an mysql query such that it would extract recent 3 transactions from table for a specific user id.
i know i can use limit.
SELECT * FROM 'transactions' WHERE 'userid'=20 LIMIT 0,3;
but how can i access attributes of different transactions which are returned as object after query? also using limit 0,3 would start search from start of table but i want to start search from bottom of table. I am using it with php.
Well, since you are not using a programming language, and just mysql, all your attributes would be displayed in the query result in the console window.
Edit:
To access your query and results, see the following article on PHP.net's website: http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
/EndEdit
To sort newest first, assuming you have a id column, use ORDER BY:
SELECT * FROM 'transactions' WHERE 'userid'=20 ORDER BY id DESC LIMIT 0,3;
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query('PREPARE mid FROM "SELECT name FROM test_user WHERE id = ?"');
// working code start
//$res = $mysqli->query('PREPARE mid FROM "SELECT name FROM test_user" ');
//$res = $mysqli->query( 'EXECUTE mid;') or die(mysqli_error($mysqli));
// working code end..
$res = $mysqli->query( 'EXECUTE mid 1;') or die(mysqli_error($mysqli));
while($resu = $res->fetch_object()) {
echo '<br>' .$resu->name;
}
Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
my php version is PHP Version 5.3.0 and mysql
mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $
I got the correct result with out using the where clause
Use the prepare function for a SELECT query:
http://php.net/manual/en/mysqli.prepare.php
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
/* close statement */
$stmt->close();
}
http://dev.mysql.com/doc/refman/5.1/en/execute.html
You need to have a using clause in the EXECUTE statement. So you could do something like:
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query('PREPARE mid FROM "SELECT name FROM test_user WHERE id = ?"');
$mysqli->query('SET #var1 = 1;');
$res = $mysqli->query( 'EXECUTE mid USING #var1;') or die(mysqli_error($mysqli));