Changing entry running order for mysql - php

I'm not sure how to do this or even if it's possible. I have a table of entries, but I'd like to change the running order of the entries. I've got a field called 'ID' which is set to auto-increment. I want the people in the back end to change the order of the entries themselves. So for example, if they move one entry up then the one above will automatically move down.
I've put up and down arrows by each entry, but am not sure what to do next. The code I've written is:
<?php
$id = $_GET['id'];
$direction = $_GET['direction'];
$menu = $_GET['menu'];
con = mysql_connect("hostname", "user", "password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table", $con);
$sql = "SELECT priority FROM Menu WHERE ID = $_GET[id]";
list($curpos) = mysql_fetch_array(mysql_query($sql));
// Find new position
if ($direction > 0)
{
// To be moved up
$sql = "SELECT priority FROM Menu WHERE priority < $curpos AND ID = $id ORDER BY priority DESC LIMIT 1";
list($newpos) = #mysql_fetch_array(mysql_query($sql));
}
else
{
// To be moved down
$sql = "SELECT priority FROM Menu WHERE priority > $curpos AND ID = $id ORDER BY priority ASC LIMIT 1";
list($newpos) = #mysql_fetch_array(mysql_query($sql));
}
if ($newpos)
{
$sql = "UPDATE Menu SET priority = $curpos WHERE priority = $newpos AND Menu = $menu";
mysql_query($sql);
$sql = "UPDATE Menu SET priority = $newpos WHERE ID = $id";
mysql_query($sql);
}
echo $msg; ?>
but this doesn't seem to do anything, I've seen it working in things like cPanel's but really don't know how to implement it myself.
I'd be grateful for any help.

Do not touch the ids for that. Create a new column "sorting" and use that. Changing the ID might cause problems and is not nice

It's better to have priority field for the records to do it. It's not good to change primary key-s of records.

If you have added the priority field, you need to change your SQL to order by priority and also to make sure the code that changes the order is updating the priority field.

Related

Find a next record after disabling a record?

I have a created a function changeIp() to disabled a record and return a new record. As you can see I am using 3 SQL query.
Is there a better way doing to reduce number of SQL queries?
function changeIp() {
// Find 1 record which is not disabled
$SQL = "SELECT * FROM ip WHERE disable = 0 order by id limit 1";
$qIp = mysql_query($SQL) or die(mysql_error());
$qrow = mysql_fetch_assoc($qIp);
// Disable a record
$id = $qrow['id'];
$SQL = "UPDATE ip set disable = 1 WHERE id = $id";
mysql_query($SQL) or die(mysql_error());
// Return the next record
$SQL = "SELECT * FROM ip WHERE disable = 0 order by id limit 1";
$qIp = mysql_query($SQL) or die(mysql_error());
$qrow = mysql_fetch_assoc($qIp);
return $qrow['ip'];
}
You should use "mysqli" or php, but that is a separate matter from your question.
Your queries are fine. You can't really do an update and select in a single statement. You can improve performance with an index on ip(id, disable). And, an index on ip(disable, id) might also be beneficial, depending on a number of factors.

PHP: How to increment a value in the table row to count views and to limit counts to one IP address

I'm using the following to inset a number into 'mviews' every time some map is viewed.
Question 1. Where in the following code do i add 'ON DUPLICATE KEY UPDATE mviews = mviews+ 1' so it can increment on duplicate?
Question 2. How do i limit counts to one IP?
Question 3. How can i limit this IP to only increment the 'mviews' only within 24 hours; only the first view will be counted on every 24 hours, the rest of the views within 24 hours after the first view are not suppose to be counted.
<?php
require_once 'db_conx.php';
$result = mysql_query( "UPDATE profiles SET mviews = '1' WHERE pid = '2' ") or die (mysql_error());
/*ON DUPLICATE KEY UPDATE mviews = mviews+ 1 */
if($result){
echo "Views + 1";
}
else {
echo "Views inser error";
}
mysql_close($con);
?>
DUPLICATE KEY UPDATE
is used with INSERT and not with UPDATE statement DOCS
count for one IP will be like this
SELECT COUNT(*) FROM profiles WHERE IP = "127.1.0.0";
[If you are not looking for what I have written above]
if IP address is your primary key then
INSERT INTO
profiles (ip,views)
VALUES ("127.1.0.0",1)
ON DUPLICATE KEY
UPDATE views=views+1;
If you want your Code to work properly[dont use mysql_* also escape user input]
<?php
require_once 'db_conx.php';
$result = mysql_query( "SELECT * FROM profiles WHERE pid =2") or die (mysql_error());
/*ON DUPLICATE KEY UPDATE mviews = mviews+ 1 */
if(mysql_num_rows($result) == 0){
mysql_query( "INSERT INTO profiles (views) value(1) ") or die (mysql_error());
}else {
mysql_query( "UPDATE profiles SET mviews = mviews +1 WHERE pid = '2' ") or die (mysql_error());
}
mysql_close($con);
?>
To both Eustatia & Arun Killu - THANK YOU!!! Because of your posted/edited solution, I was helped out of a mind-bending jam. I have to create an addendum (as my currently-resolved situation may be of help to someone reading this).
My situation was how to establish a click-tracking process for a variable-based hyperlink (i.e.);
<a target="_blank" href="<?php echo $link;?>"><b><?php echo $title;?></b></a>
I kept getting the link to echo out the representative information, open the correct, id-tagged link request (and not baffle user expectation of conventional click-behavior), but the ability to MULTIPLY log link clicks was solved by this post. NOTE TO THE SUPRA-FINICKY - YES! PDO IS THE DEFACTO STANDARD.
I apologize PROFUSELY for spreading the rank taint of deprecation, but if I understand what I'm doing now, I should be able to assimilate rudimentary PDO mastery in a 3 - 6 week period.
<?php
/** Connect to DB */
mysql_connect("localhost","database_user","pwd") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$id = mysql_real_escape_string($_GET['id']);
/** retrieve URL */
$result = mysql_query("SELECT * FROM `articles` WHERE ID = '$id'") or die(mysql_error());
/*ON DUPLICATE KEY UPDATE clicks = clicks+ 1 */
if(mysql_num_rows($result) == 0){
mysql_query("INSERT INTO `articles`(`clicks`) value(1)") or die (mysql_error());
}else {
mysql_query("UPDATE `articles` SET clicks=clicks+1 WHERE `id` = '$id'") or die (mysql_error());
}
$row = mysql_fetch_array($result);
mysql_close();
header("Location: " . $row['link']);
?>
I ended up changing the configuration of the link so the id passed the correct link to the target page;
<?php echo "<a href='pagetracking.php?id=" . $id . $link . "' target='_blank'>
<font color='#0000CC' size='5'><b>" . $row['title']. "</b></font></a>"; ?>
Thank you SO MUCH for posting Eustatia & Arun Killu, I really appreciate the tip. If anyone else here happening across this sees anything that's EXCEPTIONALLY unforgivable (even in this decrepit state, lol) - PLEASE, do - not - hesitate - to scream on it robustly. I need all the help I can get.
As promised for anyone who'd be in need of a WORKING version of this in PDO;
(this is adapted from an answer that I found here on SO, but, can't remember at the second, so I'll look it up for an edit to give the answerer credit.)
track.php
<?php
//Your database information
include '../includes/db.php';
// Fetch id (article_id) from $_GET parameter
$article_id = '';
if (isset($_GET['id'])) $article_id = intval($_GET['id']);
if (!$article_id) {
print "No article ID found!\n";
} else {
//
// Fetch Article ID
//
$sql = "SELECT * FROM `articles` WHERE article_id = :article_id";
$sth = $pdo->prepare($sql);
$sth->bindParam(":article_id", $article_id);
$sth->execute();
}
if (!$sth) {
// No article!
echo 'Invalid Article ID!\n';
} else {
// Article found!
//
// Update Clicks Column
//
$sql = "UPDATE articles SET clicks=clicks+1 WHERE article_id = :article_id";
$sth = $pdo->prepare($sql);
$sth->bindParam(':article_id', $article_id);
$sth->execute();
}
header('Location: view_article.php?id='.intval($_GET['id']));
?>
As this code is working flawlessly, for MY purposes, here's a little caveat for those looking to just blindly cut-and-paste...it updates the clicks column EACH TIME IT'S CLICKED, soooooo if you need to limit it to a certain amount of clicks or some other type of functionality, I wish you well in your endeavors (lol!). I just wanted to publish this as a current, working model of the PDO kind. In fact, I may have to end up using this solution as a basis of another mind-bending jam I'm in right now. In fact, I'm almost willing to bet dollars to donuts I'll be completely right about this move.
HTHSO
P.S. ...PDO is sooooooo annoyingly difficult...but worth it.

Updating with multiple variables with MySQL + PHP

I have 2 variables that contain a a string of text. I need to update them in the table, but out of the 20 + different variations of about 5 different scripts that I've tried out, it just doesn't update!
I can update using this:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid='" .session_id(). "' AND description = '$d'") or die(mysql_error());
but I am now working on a different page, where I need a slightly different update query. Which is:
UPDATE cart SET quantity = $q WHERE sessionid = $somethin AND description = $desc
And for that I have:
mysql_query("UPDATE cart SET quantity = $q WHERE sessionid = $o AND description = $d") or die(mysql_error());
(I have tried many variations with different quotes in different places for the above query, but nothing works!)
I have also tried:
$conn = mysql_connect("my01..com", "dbase", "2354ret345ert");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'UPDATE cart
SET quantity="'.$q.'"
WHERE sessionid="$o" AND description = "$d"';
mysql_select_db('mysql_94569_dbase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
That last one doesn't display any errors, in fact, it even tells me that it has successfully updated! But it's lying. It hasn't updated anything.
Can someone please help me out here, I am really getting sick of reading tutorial after turorial and never learning anything because they all have differnt syntax and none of it seems to work.
What I would like to do is:
UPDATE table SET columnname = $this WHERE thiscolumn = $this AND thiscolumn = $that
$this = $var
Thank you
You are missing the quotes in description and SessionID, do it like this:
mysql_query("UPDATE cart
SET quantity = '".$q."'
WHERE sessionid = '".$o."' AND description = '".$d."'");
In order to save you confusion, I would recommend start using concatenation operator (eg 'UPDATE '.$table .' SET ...')instead of writing variables directly to strings (eg. "UPDATE $table SET ...").
in this case your query would look like:
mysql_query("UPDATE cart SET quantity = ".$q." WHERE sessionid='" .session_id(). "' AND description = '".$d."'") or die(mysql_error());
This might help you to find problems with quotes and parenthesis quicker
BAD:
I had this query in php:
$query = "UPDATE users SET username = ".$nume." WHERE id = ".$userID;
That did this SQL:
UPDATE users SET username = elev WHERE id = 2
GOOD: For it to work I changed it to this php:
$query = "UPDATE users SET username = ".'"'.$nume.'"'." WHERE id = ".$userID;
That did this SQL:
UPDATE users SET username = "elev" WHERE id = 2

Php/MySQL help - random daily pick?

I'm trying to get a pick from my DB that would last for a day (daily pick). I use the following code:
$query = 'SELECT * FROM table ORDER BY rand() LIMIT 1
But as you can see it only gives me a random pick from the table, and every time I refresh the page it gets me a new random pick. How can I make the pick to last for a whole day?
Thanks in advance <3
I'm trying this:
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
But I get the following error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource. This is the part that gets broken:
$results = mysql_query($query);
while($line = mysql_fetch_assoc($results))
So... it should look like this, right? (I mean, choosing the daily random pick?)
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
I'm trying this now:
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
However, it gets me a mistake that I'm using the 'has' function on a non-object.
If you set the SEED for the rand to an integer value that changes daily, that would solve your problem
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
Would do the trick.
A sane means of doing this would be to automatically generate the pick of the day content via a cron job that was setup to run once a day.
As such, the cron job would execute the SQL you provided and store the appropriate content in a flat file/database table, etc. (or perhaps even just store the choosen id in another table for future lookup purposes).
You can try something like this:
$total = 'SELECT COUNT(*) FROM table;';
$query = 'SELECT * FROM table ORDER BY id ASC LIMIT 1 OFFSET ' . (date('Ymd') % $total) . ';';
I think you'll need to update the random picked record with "today" field = 1..
Something like this:
// ------------
// Run this 3 commands once a day
// Reset all records
mysql_query("UPDATE `table` SET `today` = 0");
// Pick one
$sql = mysql_query("SELECT `id` FROM `table` ORDER BY RAND() LIMIT 1");
$id = mysql_result($sql, 0, 'id');
// Update the record
mysql_query("UPDATE `table` SET `today` = 1 WHERE `id` = {$id}");
// ------------
// Now you can find again your "random found record":
$query = mysql_query("SELECT * FROM `table` WHERE `today` = 1");

Simple way to read single record from MySQL

What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)

Categories