I would like to make a previous and next button to scroll through the database using ID. This is my code when I am still using mysql. Right now it is changed to mysqli so I have no idea whether this code still works or not, because I keep getting null.
function getNavID($id) {
$result4= mysqli_query("SELECT
( SELECT id FROM products_list
WHERE id > '$id' LIMIT 1 ) AS nextValue,
( SELECT id FROM products_list
WHERE id < '$id' ORDER BY id DESC LIMIT 1 ) AS prevValue
FROM products_list
LIMIT 1");
if ($resultID = mysqli_fetch_array($result4)) {
return $resultID;
}
else {
return NULL;
}
}
$LinkID = getNavID($id);
if (!is_null($LinkID['prevValue']))
{
?>
Previous
<?php
}
else if (!is_null($LinkID['nextValue']))
{
?>
Next
<?php
}
else
{
echo "No Entries";
}
Besides changing mysql_query to mysqli_query, is there anything that I need to change too? Thanks in advance for the help!
try this :
global $pdo;
$id = $the_selected_id;
$stmt_a = $pdo->prepare("
(SELECT * FROM images WHERE id < ? ORDER BY id DESC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MAX(id) FROM images)) LIMIT 1");
$stmt_b = $pdo->prepare("
(SELECT * FROM images WHERE id > ? ORDER BY id ASC LIMIT 1)
UNION (SELECT * FROM images WHERE id = (SELECT MIN(id) FROM images)) LIMIT 1");
// $vars = array(':id' => $id);
$prev = $stmt_a->execute(array( (int)$id ));
$next = $stmt_b->execute(array( (int)$id ));
if ($stmt_a->rowCount() > 0) {
while($row = $stmt_a->fetch(PDO::FETCH_ASSOC)) {
echo 'Previous';
}
} else {
echo 'no previous';
}
if ($stmt_b->rowCount() > 0) {
while($row = $stmt_b->fetch(PDO::FETCH_ASSOC)) {
echo 'Next';
}
} else {
echo 'no next';
entre your db conection befor sentax like this:
<?
//enter your MySQL database host name, often it is not necessary to edit this line
$db_host = "localhost";
//enter your MySQL database username
$db_username = "your user name";
//enter your MySQL database password
$db_password = "your passwor";
//enter your MySQL database name
$db_name = "your db name";
//URL to the the site
$ScriptPath = "http://www.your-site.com/";
$db = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error($db));
mysqli_select_db($db, $db_name) or die("Error " . mysqli_error($db));
function getNavID($id) {
$result4= mysqli_query($db, "SELECT
( SELECT id FROM products_list
WHERE id > '$id' LIMIT 1 ) AS nextValue,
( SELECT id FROM products_list
WHERE id < '$id' ORDER BY id DESC LIMIT 1 ) AS prevValue
FROM products_list
LIMIT 1");
if ($resultID = mysqli_fetch_array($db, $result4)) {
return $resultID;
}
else {
return NULL;
}
}
$LinkID = getNavID($id);
if (!is_null($LinkID['prevValue']))
{
?>
Previous
<?php
}
else if (!is_null($LinkID['nextValue']))
{
?>
Next
<?php
}
else
{
echo "No Entries";
}
?>
Related
I am not able to get max value from SQLite with PHP but getting 0 (zero) but If I run the query in SQLite I am getting COrrect value. The code is shown below.
class MyDB extends SQLite3 {
function __construct() {
$this->open('data.db');
}
}
$con = new MyDB();
$sql = "SELECT MAX(sd_id) FROM stu_data ORDER BY sd_id DESC LIMIT 1";
$result = $con->query($sql);
if ($result) {
if($row = $result->fetchArray(PDO::FETCH_ASSOC)) {
$lclId = $row[0]["MAX(sd_id)"] + 1;
$lclNo = $lclId;
}
} else {
$lclNo = '1';
}
Here I am Getting $row[0]["sd_id"] AS zero (0) always.
Your return value is not called sd_id as you have not aliased the value. You can either use
$row['MAX(sd_id)']
or better yet supply a column alias in the query:
SELECT MAX(sd_id) AS max_sd_id FROM stu_data
Then you can refer to it as $row['max_sd_id']. e.g.
$sql = "SELECT MAX(sd_id) AS max_sd_id FROM stu_data ORDER BY sd_id DESC LIMIT 1";
$result = $con->query($sql);
if ($result) {
if($row = $result->fetchArray(PDO::FETCH_ASSOC)) {
$lclId = $row['max_sd_id'] + 1;
$lclNo = $lclId;
}
} else {
$lclNo = '1';
}
Note that the ORDER BY sd_id DESC LIMIT 1 in your query is meaningless as it will only return 1 value anyway.
class MyDB extends SQLite3 {
function __construct() {
$this->open('data.db');
}
}
$con = new MyDB();
$sql = "SELECT MAX(sd_id) FROM stu_data ORDER BY sd_id DESC LIMIT 1";
$result = $con->query($sql);
if ($result) {
if($row = $result->fetchArray(SQLITE3_ASSOC)) {
$lclId = $row[0]["MAX(sd_id)"] + 1;
$lclNo = $lclId;
}
} else {
$lclNo = '1';
}
The Difference is Need to use fetchArray(SQLITE3_ASSOC) Instead of fetchArray(PDO::FETCH_ASSOC)
I have over 40'000 entries and each is assigned to a "list_name"
I am basically trying to get just the list_name value echo'd out
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
$groupr = mysqli_fetch_assoc($groupq);
do {
echo $groupr['list_name'];
} while($groupr = mysqli_fetch_assoc($groupq));
however its only displaying 1 entry then no more ..
https://imgur.com/a/3rnXGet
Try this.
$groupq = mysqli_query($dbc, "SELECT * FROM `products-full` GROUP BY `list_name`");
while($groupr = mysqli_fetch_assoc($groupq)){
echo $groupr['list_name'];
}
$database = "sample" //replace your database name here
$conn=new mysqli("localhost","root","",$database); // here username is root and password is null , change it according to yours
if($conn->connect_error)
{
echo $conn->connect_error;
die("sorry database connection failed");
}
$sql = "SELECT * FROM products-full GROUP BY list_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row['list_name'];
}
}
thats it
try this
$groupq = mysqli_query($dbc, "SELECT list_name, count(*) FROM `products-full` GROUP BY
`list_name`");
while($groupr = mysqli_fetch_assoc($groupq)) {
echo $groupr['list_name'];
}
This is the code that is not working:
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
//THIS SHOULD NOT BE RUNNING
}
I've verified over and over in phpMyAdmin and the text_id in the table and $last_id are both the integer value '1'. That being said, the condition equates to true every time the code runs.
Am I messing this code up, or is my thinking improper?
Here is entire script:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$last_id_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$last_id_query = "SELECT alias FROM $last_id_table WHERE alias = '$alias'";
$last_id_result = mysqli_query($connection,$last_id_query);
$last_id_rows = mysqli_fetch_array($last_id_result);
if ($last_id_rows['alias'] === $alias)
{
$last_id = $last_id_rows['last_id'];
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
$last_row_id = $row['text_id'];
}
}
//UPDATE LAST SYNC ID
$update_query = "UPDATE $last_id_table SET last_id = '$last_row_id' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "INSERT INTO $last_id_table (alias, last_id) VALUES('$alias','-1')";
mysqli_query($connection,$update_query);
}
?>
You should change ;
WHERE text_id > '$last_id'
to
WHERE text_id > $last_id
text_id column is integer and can't be compared like string.
I'm working on a school project where I need to allow users to vote on pictures. Users can a picture up or down. It's the idea that they can change their vote anytime, but they can't undo their vote, so once they voted it's either up or down.
I've been trying some things but I can't seem to get it to work. It works when an user pressed an upvote for the first time, then the user is able to change his vote to a downvote. But when he tries to upvote again, nothing is happening this has been bugging me for a while now, I would appreciated any help.
Here is my code so far:
if (isset($_SESSION['loggedin'])) {
$result = mysql_query("SELECT * FROM user2pics WHERE picid = $id AND userid = $user");
if (mysql_num_rows($result) == 0) {
$votes_up = $cur_votes[0] + 1;
$resultaat = mysql_query("UPDATE pics SET likes = $votes_up WHERE picid = $id");
if ($resultaat) {
$query = mysql_query("INSERT INTO user2pics (picid, userid, vote) VALUES ($id, $user, 1)");
if ($query) {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
} elseif (!$query) {
echo "Failed!";
}
} elseif (!$resultaat) {
echo "Failed insert in pics!";
}
} else {
$row = mysql_fetch_array($result);
if ($row['vote'] == 0) {
$votes_down = $cur_votes[0] + 1;
$result = mysql_query("UPDATE pics SET likes = $votes_up WHERE picid = $id");
if ($result) {
$resultaat = $mysqli -> prepare("UPDATE user2pics SET vote = 1 WHERE picid = $id AND userid = $user");
$resultaat -> execute();
$effectiveVote = getEffectiveVotes($id);
if ($resultaat -> affected_rows == 1) {
echo $effectiveVote . " votes";
}
}
} else {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
}
}
} else {
echo "Please login first!";
}
} elseif ($action == 'vote_down'){
if (isset($_SESSION['loggedin'])) {
$result = mysql_query("SELECT * FROM user2pics WHERE picid = $id AND userid = $user");
if (mysql_num_rows($result) == 0) {
$votes_down = $cur_votes[1] + 1;
$resultaat = mysql_query("UPDATE pics SET dislikes = $votes_down WHERE picid = $id");
if ($resultaat) {
$query = mysql_query("INSERT INTO user2pics (picid, userid, vote) VALUES ($id, $user, 0)");
if ($query) {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
} elseif (!$query) {
echo "Failed to dislike!";
}
} elseif (!$resultaat) {
echo "Failed insert in pics!";
}
} else {
$row = mysql_fetch_array($result);
if ($row['vote'] == 1) {
$votes_down = $cur_votes[1] + 1;
$result = mysql_query("UPDATE pics SET dislikes = $votes_down WHERE picid = $id");
if ($result) {
$resultaat = $mysqli -> prepare("UPDATE user2pics SET vote = 0 WHERE picid = $id AND userid = $user");
$resultaat -> execute();
$effectiveVote = getEffectiveVotes($id);
if ($resultaat -> affected_rows == 1) {
echo $effectiveVote . " votes";
}
}
} else {
$effectiveVote = getEffectiveVotes($id);
echo $effectiveVote . " votes";
}
}
} else {
echo "Please login first!";
}
}
$cur_votes is defined as:
$cur_votes = getAllVotes($id);
function getAllVotes($id) {
$votes = array();
$q = "SELECT * FROM pics WHERE picid = $id";
$r = mysql_query($q);
if (mysql_num_rows($r) == 1)//id found in the table
{
$row = mysql_fetch_assoc($r);
$votes[0] = $row['likes'];
$votes[1] = $row['dislikes'];
}
return $votes;
}
function getEffectiveVotes($id) {
/**
Returns an integer
**/
$votes = getAllVotes($id);
$effectiveVote = $votes[0] - $votes[1];
return $effectiveVote;
}
You're duplicating functionality by storing 'likes' in two places.
I didn't look at your weak entity (table for users and votes) so let's assume it will have three fields: user_id, item_id and vote TINYINT. Primary key on user_id and item_id so the same user can only have one vote per item.
Set vote to 1 or -1 depending on up or down, instead of storing likes in the item table, calculate total vote for an item dynamically like this:
SELECT SUM(vote) FROM user_votes WHERE item_id = ?;
If you only want positive votes, do this:
SELECT SUM(vote) FROM user_votes WHERE item_id = ? AND vote = 1;
When the user wants to record or change his vote, you can use REPLACE INTO syntax (thanks to Anigel for the suggestion -- I totally missed it) in order to store the user's new vote:
REPLACE INTO user_votes (user_id, item_id, vote) VALUES (?, ?, ?);
$mpn = $P[0];
$qty = $P[14];
$mysql_connection = mysql_connect('localhost', 'my_db', 'my_pass');
if (!$mysql_connection) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db('my_db', $mysql_connection);
$id = mysql_query("SELECT productid FROM my_table_2 WHERE value = '$mpn'");
if (!$id) {
return("XXX-99999");
}
mysql_select_db('my_db', $mysql_connection);
$sku = mysql_query("SELECT productcode FROM my_table WHERE productid = $id");
if (!$sku) {
return("XXX-99999");
}
mysql_select_db('my_db', $mysql_connection);
$qty2 = mysql_query("SELECT avail FROM my_table WHERE productcode = '$sku'");
if (!$qty2) {
return("XXX-99999");
}
if ($qty2 <1 && $qty >0 && $qty2 != $qty) {
return($sku);
}
else {
return("XXX-99999");
}
I'm trying to match Manufacturers part numbers from Product feed and database to accomplish putting out of stock products from main source to secondary source. It does not work. What I am doing wrong?
This has been edited to try and explain the situation more clearly. First this is going into an app and is a snippit to be used by that app. Hence mysql instead of mysqli. The variable $mpn in the first query comes from $mpn = ($P[0]); at the top. It is in a feed and not in the database as a column. $sku in the second query comes from the result of the first query and is not in the database as a column. The app loops this code for each line of the feed.
The above fails to achieve the desired effect of providing the last argument even though I know it for sure should (I set it up). Given the new explaination can somebody help?
$mpn = ($P[0]);
$qty = ($P[14]);
$mysql_connection = mysql_connect('localhost', 'user', 'pass' );
if (!$mysql_connection) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db('db', $mysql_connection);
$tmp1 = mysql_query("SELECT productcode FROM table1 WHERE mpn != '' && mpn = '$mpn'")or die(mysql_error());
$row1 = mysql_fetch_array($tmp1, MYSQL_BOTH);
$sku = $row1[0];
$tmp2 = mysql_query("SELECT avail FROM table1 WHERE productcode = '$sku'")or die(mysql_error());
$row2 = mysql_fetch_array($tmp2, MYSQL_NUM);
$qty2 = $row2[0];
if ($qty2 <=0 && $qty >0) {
return($sku);
}
else {
return("XXX-99999");
}
You have to fetch the data after mysql_query(look into mysqli instead) using mysql_fetch_array. After fetching assign $row1 = mysql_fetch_array($id); and then you can call the row and column name $row1['productid'];. You also do not need to open assign the database before every call. You can only do it once before running the queries and then run mysql_close($mysql_connection)
$mpn = $P[0];
$qty = $P[14];
$mysql_connection = mysql_connect('localhost', 'my_db', 'my_pass');
if (!$mysql_connection) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db('my_db', $mysql_connection);
$id = mysql_query("SELECT productid FROM my_table_2 WHERE value = '$mpn'");
$row1 = mysql_fetch_array($id);
if (!$id) { return("XXX-99999");
}
$sku = mysql_query("SELECT productcode FROM my_table WHERE productid = $row1['productid']");
$row2 = mysql_fetch_array($sku);
if (!$sku) { return("XXX-99999");
}
$qty2 = mysql_query("SELECT avail FROM my_table WHERE productcode = '$row2['productcode']'");
$row3 = mysql_fetch_array($qty2);
if (!$qty2) { return("XXX-99999");
}
if ($row3['avail'] <1 && $qty >0 && $row3['avail'] != $qty) { return($row['productcode']);
}
else {return("XXX-99999");
}
mysql_close($mysql_connection);
This should give you more or less an idea. Use as reference: http://www.php.net/manual/en/function.mysql-connect.php
Here:
$sku = mysql_query("SELECT productcode FROM my_table WHERE productid = $id");
I think it should look like:
$sku = mysql_query("SELECT productcode FROM my_table WHERE productid = '$id' ");