Creating next button to loop through mysql table - php

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 */

Related

Mysql restrict on delete check

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);
?>

Check if value exists in MySQL table

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)

Can't get mysql_query to return any values that exist in the database

I'm using the following snippet:
mysql_connect($host,$user,$password);
$sql = "SELECT FROM ec_opps WHERE id=" . $_GET["UPDATE"];
$item = mysql_query($sql);
mysql_close();
print_r($item);
To try and retrieve data based on the UPDATE value. This value prints to the page accurately, and I know the IDs I'm requesting exist in the database. The print_r($item) function returns no result, not even an empty array, so I'm confused as to where I'm going wrong.
I know it isn't best practise to use MySQL like this, but I'm doing it for a reason.
You're missing columns to be selected in your SELECT query, or you can select all by putting *, which means selecting all column.
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"]."'";
Your query is very prone to SQL injections.
You should refrain from using MySQL. It's deprecated already. You should be at least using MySQLi_* instead.
<?php
/* ESTABLISH CONNECTION */
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT column1, column2 FROM ec_opps WHERE id=?"; /* REPLACE NEEDED COLUMN OR ADD/REMOVE COLUMNS TO BE SELECTED */
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("s", $_GET["UPDATE"]); /* BIND GET VALUE TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($column1,$column2); /* BIND RESULTS */
while ($stmt->fetch()) { /* FETCH RESULTS */
printf ("%s (%s)\n", $column1, $column2);
}
$stmt->close();
}
$mysqli->close();
?>
Replace with this code
$sql = "SELECT * FROM ec_opps WHERE id=" . $_GET["UPDATE"];
You are missing * in your query.
You need to use:
SELECT * FROM
instead of
SELECT FROM
There is a syntax error in the query. It is missing *. Try with -
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"] . "'";
Please avoid using mysql. Try to use mysqli or PDO. mysql is deprecated now.

PHP/MySQL Count Num Rows

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 */

Passing array of values from form to sql query WHERE IN clause

I have a form with a number of checkboxes, which are generated from unique values in a MySQL table:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$query5="SELECT distinct from_user from tracks WHERE uploaded_page='$this_path_short' ORDER BY from_user";
$result5=mysql_query($query5) or die(mysql_error());
while ($row = mysql_fetch_array($result5)) {
$from_user = $row['from_user'];
echo "<input type=\"checkbox\" name=\"from_user[]\" value=\"AND ".$from_user."\" checked=\"checked\">".$from_user."<br>";
}
?>
<input type="submit" name="submit" value="filter"><br>
I would then like to pass the array of 'from_user' values to another MySQL query on the page. I can get the values like this:
$names=implode(" ", $_POST['from_user']);
But I am not sure how to include this array in the following MySQL query:
$query1="SELECT * FROM tracks WHERE from_user IN **array goes here**)";
$query1='SELECT * FROM tracks WHERE from_user IN ('.implode(',',$_POST['from_user']).')';
Remove the AND so the checkbox value looks like this:
echo "<input type=\"checkbox\" name=\"from_user[]\" value=\"".$from_user."\" checked=\"checked\">".$from_user."<br>";
}
IN expects comma separated values:
$names=implode(",", $_POST['from_user']);
$query1="SELECT * FROM tracks WHERE from_user IN (".$names."))";
!!!! BUT: Please, please, please use prepared statements because your code is wide open to SQL Injection:
http://php.net/manual/de/mysqli.prepare.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();
}
$result = null;
$names = implode(",", $_POST['from_user']);
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM tracks WHERE from_user IN (?)")) {
/* bind parameters for markers */
$stmt->bind_param("s", $names);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($result);
/* fetch value */
$stmt->fetch();
print_r($result);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();

Categories