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;
Related
I have a mysql database with restrict on delete setting.
I have this delete query:
if(isset($_POST['delete_id']))
{
$sqldelete="DELETE FROM tblAcqDetail WHERE ID=".$_POST['delete_id'];
$resultdelete = $conn->query($sqldelete);
}
How can I check if the query does delete anything or is restricted by mysql.
I need to run an update query (see below) only if the delete query works.
I tried:
if ($resultdelete->affected_rows> 0) {
// Escape user inputs for security
$status = mysqli_real_escape_string($link, $_POST['status']);
if(isset($_POST['status']))
{
$setsql="UPDATE tblInvoiceDetail SET TRANSFER = '0' WHERE ID='$status'";
$setresult = $conn->query($setsql);
}
}
I also tried
if ($resultdelete->num_rows > 0) {
And also :
if ($resultdelete) {
All of the above stop the update query from executing.
You can use mysqli_affected_rows().
From the docs:
Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query.
Note this is run on the connection object, not the result. So use $conn->affected_rows instead of $resultdelete->affected_rows.
Rather than passing $resultdelete in to mysqli_affected_rows you actually want to pass the DB link (returned by mysqli_connect) which will give you the number of rows affected by the previous query
$sqldelete="DELETE FROM tblAcqDetail WHERE ID=".$_POST['delete_id'];
$resultdelete = $conn->query($sqldelete);
if ($conn->affected_rows > 0) {// pass db link here
Read http://php.net/manual/en/mysqli.affected-rows.php
Your problem is you're referencing the wrong thing
if ($resultdelete->affected_rows> 0) {
But
$resultdelete = $conn->query($sqldelete);
only returns a boolean(emphasis mine).
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE
You want to reference the connection itself for how many rows were affected
if ($conn->affected_rows> 0) {
If condition should be
if ($conn->affected_rows> 0){}
not
if ($resultdelete->affected_rows> 0){}
You're using it wrong if ($resultdelete->affected_rows> 0) you're using num_rows() syntax with the >0 bit.
The connection is passed to the function and not from the result set.
RTM http://php.net/manual/en/mysqli.affected-rows.php
Object oriented style
int $mysqli->affected_rows;
Procedural style
int mysqli_affected_rows ( mysqli $link )
From the manual:
<?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();
}
/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);
$mysqli->query("ALTER TABLE Language ADD Status int default 0");
/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);
/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);
/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);
$result->close();
/* Delete table Language */
$mysqli->query("DROP TABLE Language");
/* close connection */
$mysqli->close();
?>
Procedural style
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
if (!$link) {
printf("Can't connect to localhost. Error: %s\n", mysqli_connect_error());
exit();
}
/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));
mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");
/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));
/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));
/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));
mysqli_free_result($result);
/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");
/* close connection */
mysqli_close($link);
?>
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 want to truncate a table via PHP. It has some foreign keys, so I use the little trick where I set my foreign key check to zero:
$query_truncate_extension = "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE extension; SET FOREIGN_KEY_CHECKS = 1;";
When I execute the script, the mysqli_error() gives me the following 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 'TRUNCATE TABLE extension; SET FOREIGN_KEY_CHECKS = 1' at line 1
So my table doesn't get truncated at all. But the weird thing is when I put this exact same query in the SQL-query section in phpmyadmin, it doesn't throw an error at all and my table is empty afterwards.
So my question is: why does this code gives an error in PHP, but not in phpmyadmin and how do I solve this?
Thanks in advance!
If you wan to run multiple queries in one call then you need to use
mysqli_multi_query()
This is a function allows to run one or multiple queries which are concatenated by a semicolon.
To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().
You can read more detail here.
http://php.net/manual/en/mysqli.multi-query.php
--------- Example Program at the link above -------------
$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 CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
You can change it according to your requirement.
Use single query in single call like
$query_truncate_extension = "SET FOREIGN_KEY_CHECKS = 0"
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 */
I'd like to know if there is a simple way to fetch data from mysql tables with "correct" data types? What i mean, if field type is for example INT or SMALLINT is it possible to pass those types directly to PHP as integers?
I did some searching and found mysqli_fetch_fields, but for SMALLIT type is 2, for INT 3 and so on. It could be done that way, but it looks rather clumsy workaround. Is there any better way?
I'm using PHP and mysqli.
Thank you.
The most straightforward way is to build your own database handler on top of the mysqli calls that does that for you.
http://www.php.net/manual/en/mysqli-result.fetch-field-direct.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, SurfaceArea from Country ORDER BY Name LIMIT 5";
if ($result = $mysqli->query($query)) {
/* Get field information for column 'SurfaceArea' */
$finfo = $result->fetch_field_direct(1);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);
$result->close();
}
/* close connection */
$mysqli->close();
?>
You can use this code
SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'yourtablename replace your table name' AND COLUMN_NAME = 'tablecolumnname replace your table column name';
Use this before run your main query and after when you get your datatype then execute your operation.