Insert new column, increment all rows - mysql

Is this possible using only mysql:
Insert a new column and example - "pos".
Every row in the table has to have unique,incresing value of "pos" like - 1,2,3,4,5.
In php this would be an easy job:
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$counter = 0;
while($row = mysql_fetch_array($result)){
mysql_query( "UPDATE example SET pos = ".++$counter." WHERE id = ".$row['id']." );
}

As already suggested, the most efficient solution is to use auto incremental on pos.
Alternatively if your use case do not permit you, then try similar:
"UPDATE example SET pos = ((select max(pos) from example) +1) WHERE id
= ".$row['id']."

yes you can do it like that
UPDATE example SET pos = pos+1 WHERE id = ".$row['id']."

Give your pos mysql field the auto_increment attribute - this will index it, make it unique, and increment by 1 on each insert

Related

Updating Multiple Column on MySQL

I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle

update enum value from 1 to 0 mysql?

i'm trying to get this script to update my enum column 'read_message' in my 'ptb_messages' table but it just doesn't do anything. the rest of the script works fine but it's just ignoring the request to update 'read_message from 1 to 0.
can someone please show me where im going wrong? thanks
<?php
session_start();
include 'includes/_config/connection.php';
$subject = $_POST['subject'];
$message_id=$_GET['to'];
$textarea = $_POST['textarea'];
$query = mysql_query("SELECT content FROM ptb_messages WHERE id='".$message_id."'");
$results=mysql_fetch_array($query);
$result=$results['0'];
if($result && $textarea) {
$sql = mysql_query("UPDATE ptb_messages SET content ='".addslashes($textarea)."' WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET date_sent = LOCALTIME WHERE id='".$message_id."'");
$query = mysql_query("SELECT suibject FROM ptb_messages WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET subject = IF(subject LIKE '%:reply', subject, CONCAT(subject, ':reply')) WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET read_message = '0' WHERE id=".$message_id."");
$_SESSION['message_sent']="<div class=\"message_sent\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}#confirm");
}
?>
You're hitting an edge case in MySQL. enum fields can have their values to referred to by the actual value, or their INDEX in the list of allowable values. You're trying to use 0, which MySQL is interpreting as index 0 of the list, which internally is the empty string.
e.g.
myfield ENUM('one', 'two', 'three')
myfield = 'two' => 'two'
myfield = 1 => 'one'
myfield = 0 => '', not in list, ignore...
If you just need a 0/1 value for a field, why not use an actual BIT field, which is already 0/1/null-only? Using enums for purely numeric values just runs into this value-v.s.-index problem.

Trouble Inserting An Array of Information into a MySQL Database

I am having an issue with inserting an array of information into a mysql database. Basically I built a sortable gallery similar to Facebook's photo albums that can be arranged by moving the div to a new spot with jquery's sortable function.
I am using Ajax to call a php file which will inser the new order of the div's into the DB. The information is being passed correctly, it is just not being inserted correctly.
The error I am receiving is:
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 'Array' at line 1
The Php code is:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
If I remove the mysql_query function and just do a print_r, I get:
Array
(
[0] => UPDATE table SET order = '0' WHERE id = '2'
[1] => UPDATE table SET order = '1' WHERE id = '4'
[2] => UPDATE table SET order = '2' WHERE id = '3'
[3] => UPDATE table SET order = '3' WHERE id = '1'
[4] => UPDATE table SET order = '4' WHERE id = '5'
[5] => UPDATE table SET order = '5' WHERE id = '6'
)
This is the first time I have tried to do something like this. Any help would be great.
Thank you in advance for the help!
In mysql_query($sql) $sql is an array, therefore it's value is simply Array. When you assign $sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'"; simply make this line $sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";. That should solve your problem.
EDIT:
You can leave the [] and simply remove the mysql_query from where it is. After your foreach list item, add this:
foreach($sql as $query) {
mysql_query($query);
}
Sounds like there is some confusion about what the [] operator does. You use [] when you want to append an element to the end of an existing array.
For example:
$sql = array();
$sql[] = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will produce the error you are seeing
Versus:
$sql = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will work
You should rewrite your code as such:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
That will do what you are intending. However, this is still not a good idea, since you are passing untrusted $_GET data directly to the database. I could, for example, call your script with a string like:
http://yoursite.com/yourscript.php?listItem=1'%3B%20DROP%20TABLE%20yourtable%3B
Since the value of listItem is going directly to the database -- and the $item >= 1 check is insufficient, since PHP will evaluate a string as an integer if it begins with numeric data -- all I have to do is add a single quote to terminate the previous query, and I am then free to inject whatever SQL command I'd like; this is a basic SQL injection attack. Whenever you write database-touching code, you should cleanse any input that might be going to the database. A final version of your code might look like:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) { // this check may or may not be needed depending on its purpose
$sql = 'UPDATE table SET order = "' . mysql_real_escape_string($position) . '" WHERE id = "' . mysql_real_escape_string($item) . '"';
mysql_query($sql) or die(mysql_error());
}
}
There are other ways to cleanse input data as well, that is just one of them. Hope that helps.

Insert on first request; update on all subsequent requests

I'm inserting a row into a MySQL database table. On the first insertion I want a new row to be added, but after that I just want that row to be updated. Here's how I'm doing it. An Ajax request calls the following php file:
<?php
include "base.php";
$bookID = $_POST['bookID'];
$shelfID = $_POST['shelfID'];
$userID = $_SESSION['user_id'];
$query = mysql_query("SELECT shelfID FROM shelves WHERE userID = '$userID' AND shelfID = '$shelfID' AND bookID = '$bookID'");
if (mysql_num_rows($query) == 0) {
$insert = "INSERT INTO shelves (bookID,shelfID,userID) VALUES ('$bookID','$shelfID','$userID')";
mysql_query($insert) or die(mysql_error());
} elseif (mysql_num_rows($query) == 1) { //ie row already exists
$update = "UPDATE shelves SET shelfID = '$shelfID' WHERE userID = '$userID' AND bookID = '$bookID'";
mysql_query($update) or die(mysql_error());
}
?>
As it stands it adds a new row every time.
You should consider using PDO for data access. There is a discussion on what you need to do here: PDO Insert on Duplicate Key Update
I'd flag this as duplicate, but that question is specifically discussing PDO.
You can use the INSERT ... ON DUPLICATE KEY UPDATE syntax. As long as you have a unique index on the data set (i.e. userid + shelfid + bookid) you are inserting, it will do an update instead.
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

mysql use fields value while insert a record

A simple question!:
Can I use my field value in an insert query?
For example, I've a field named id, it is an auto_increment field. i want to add this field value to another field. while I'm inserting it.
A simple php code of my need:
$query_1 = mysql_query("INSERT INTO table (name) VALUES ('abcd')"); // id automatically increment
$query_2 = mysql_query("SELECT id FROM table WHERE name = 'abcd'"); // selects previous id
// fetches result //
$query_3 = mysql_query("UPDATE table SET code = '" . $id + 1000 . "' WHERE id = '" . $id . "');
Can you convert it to just 1 query?
Thanks ...
I don't think you can do it in one query but you can do it in 2 for sure:
mysql_query("INSERT INTO table (name) VALUES ('abcd')");
$id = mysql_insert_id();
mysql_query("UPDATE table SET code = '" . $id + 1000 . "' WHERE id = '" . $id . "');
Here's how you do it with one query:
$query_1 = "INSERT INTO table (note) VALUES ('abcd'); UPDATE table SET code = LAST_INSERT_ID() + 1000 where id = LAST_INSERT_ID()";
I can't remember if mysql allows multiple queries in one command - I think maybe not, so try this:
$query_1 = "INSERT INTO table (note) VALUES ('abcd')";
$query_2 = "UPDATE table SET code = id + 1000 where id = LAST_INSERT_ID()";