I have a table without an AI index. I had to trim data from a colum, and now I need to update with result from trim, but with the cod I have now, only updates with the same value, last value from that array.
$i=0;
while ($row = $column->fetch_assoc()) {
$arr[$i] = trim($row['profile_value'],"\"");
$db->query("UPDATE `vwfl5_user_profiles` SET profile_value='".$arr[$i]."'");
$i++;
}
Thanks!
You don't really need a loop for this. Just do it with one query.
$db->query("UPDATE `vwfl5_user_profiles` SET profile_value= TRIM( '\"' FROM profile_value)");
If you don't want to update every record, just add a WHERE clause with whatever criteria you used to get the results you are looping over.
$db->query("UPDATE `vwfl5_user_profiles`
SET profile_value = TRIM( '\"' FROM profile_value) WHERE... ");
2 things:
Shouldn't you update a specific row? Ie: "UPDATE `vwfl5_user_profiles` SET profile_value='".$arr[$i]."' WHERE id=$row[id]" (given there is an id and is integer)
I think you can do that with Trim Function
You should add WHERE clause with table primary key to identify each item in the db:
$i=0;
while ($row = $column->fetch_assoc()) {
$arr[$i] = trim($row['profile_value'],"\"");
$db->query("UPDATE `vwfl5_user_profiles` SET profile_value='".$arr[$i]."' WHERE id = " . $row['id'] . "");
$i++;
}
Related
code:
<?php
$this->db->select('*');
$this->db->from('bugs');
$where = "project_name = '".$project."'";
$this->db->where($where);
$sql = $this->db->get();
$res = $sql->num_rows();
if($res === 0)
{
$i = 1;
foreach ($bug as $row)
{
echo $i;
}
}
else
{
$i = 1;
foreach ($bug as $row)
{
echo ++$i;
}
}
?>
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
In this code I have a table name bugs where I have a column i.e. bug_id. Now, I want to insert data into my table if table row having no value it insert bug_id = 1 and after that insert 2 and then 3 and so on. But now when I click on submit button it insert bug_id = 1 and then 2 but when I click on third it insert again bug_id 2 . So, How can I fix this problem?Please help me.
Thank You
MySQL has integrated AUTO_INCREMENT. Either you log into phpMyAdmin and change the properties of your bug_id field by clicking on edit, then selecting the "A_I" field.
Or you can do it with a SQL query:
ALTER TABLE YOUR_TABLE MODIFY bug_id INTEGER NOT NULL AUTO_INCREMENT;
If #Twinfriends answer doesn't fit your needs (but that should be the correct way to do that, you shouldn't reinvent the wheel) then maybe the problem is with your:
$data = array(
'project_name'=>$this->input->post('project'),
'bug_id'=>$this->input->post('bug_id'),
);
$query = $this->db->insert('bugs',$data);
Since you are actually using $this->input->post('bug_id') as your new id, maybe you want to use something else?
Where does your $bug var come from? To be sure of not getting duplicated ids or wrong one you could add to your MySql query something like "ORDER BY bug_id DESC LIMIT 1" (so that you take 1 row as result with the highest bug_id) and then just use that result + 1 as the new id
I have around 1000 records in my MySQL database. I recently added a new column called UniqueKey and I want to update all rows in my table with a random, unique key.
This is what I got:
$updatequery = "SELECT * FROM pictures";
$resultt = $conn->query($updatequery);
while ($roww = $resultt->fetch_array()) {
$rowws[] = $roww;
}
foreach($rowws as &$roww) {
$UniqueKey = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey'";
mysqli_query($conn, $sqlupdate);
}
The problem here is as follows. It DOES create a UniqueKey, but it uploads this new random value to ALL my rows. How can I do this?:
generate random key by $UniqyeKey
Insert this key in the first row
regenerate a new key and insert this in the next row
etc etc
Thanks in advance! Have been trying to fix this for hours..
There is no need to use the extra foreach loop. You can do the all the job within the while loop itself, as follows:
while ($roww = $resultt->fetch_array()) {
$UniqueKey = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey' WHERE id = '".$roww['id']."'";
mysqli_query($conn, $sqlupdate);
}
Note: The given example assumes that id is the Primary Key in your table. You can change that accordingly
Related: Setting value for one column of all records in table
Without a where clause an update updates all the records. So update your query from:
UPDATE pictures SET UniqueKey = '$UniqueKey'
to:
UPDATE pictures
SET UniqueKey = '$UniqueKey'
where id = ?
or something like that where it identifies the one record you want to update each time.
Also you don't need the foreach, do it all in the while loop.
The others have already solved the issue with updating all rows at once.
But if you truly want to have unique values, I would suggest to add a UNIQUE constraint to your UniqueKey column.
In addition, you could put your generation of the unique key and the update query in a do-while loop like this:
while ($roww = $resultt->fetch_array()) {
do {
$UniqueKey = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey' WHERE id = '".$roww['id']."'";
} while (!mysqli_query($conn, $sqlupdate))
}
The combination of these two steps would ensure that the key is Unique and is properly inserted in the database.
You need to set a Where clause to update the rows you want. Foreach only loops you through the result set you get from the select, you are not actually inside the database. When you do
$updatequery = "SELECT * FROM pictures";
$resultt = $conn->query($updatequery);
You are assigning to $resultt the result of that query, you are not actually 'inside' the database. When you then query:
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey'";
mysqli_query($conn, $sqlupdate);
You are updating ALL UniqueKeys to the same one. Your foreach loop does nothing, it only loops through your result set and updates the key $rowss times. Basically, you are updating all keys #rowss times. I assume you have an autoincrementing ID in your table?
If so, you can delete your foreach loop and replace it with:
$idresult = $conn->query("SELECT id FROM pictures");
while ($row = $idresult->fetch_assoc()){
mysqli_query($conn, "UPDATE pictures SET UniqueKey = '$UniqueKey' WHERE id = " . $row['id'];
}
You're updating every single row because you're not using a WHERE clause.
Do something like this:
foreach($rowws as &$roww) {
$UniqueKey = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6);
$sqlupdate = "UPDATE pictures SET UniqueKey = '$UniqueKey' WHERE primary_key=".$rowws['primary_key'];
mysqli_query($conn, $sqlupdate);
}
Where primary_key is the PK column of your table.
I have a dynamic table in my db, that columns are altered and deleted from other scripts. Because there is a chance that all those extra columns might hold null or empty values eventually i want to have a 'cleanup' action somewhere that checks for those cells, and if all are empty, to drop the whole row.
The ones in red are the ones i want to check. If both columns are null or empty WHERE customers_id = 1, then DELETE row.
Like i said this is just an example...There could be 5 or 10 columns after customers_id. I need to check them all if they are empty.
I can get all the names of those extra columns in a string like this:
$temparray = array();
$q = mydb_query("SHOW COLUMNS FROM $table WHERE field NOT REGEXP 'id|customers_id'");
while($row = mydb_fetch_array($q)){
$temparray[] = $row['Field'];
}
$forSQL = " '".implode("', '", $temparray)."' "; // gives 'client_custom_contact_person', 'client_custom_password'
$forPHP = implode(", ", $temparray); //gives client_custom_contact_person, client_custom_password
What is the fastest way to check if all those column values are empty to drop that row ?
Should i go with a php foreach function ? Or is there a faster mysql query i could do ?
-Thanks
Figured it out. Using the $forPHP string:
$q2 = mydb_query("SELECT $forPHP FROM $table WHERE customers_id = 1");
$res = mydb_fetch_assoc($q2);
if(!array_filter($res)) {
//If all are empty then
mydb_query("DELETE FROM $table WHERE customers_id = 1");
}
Currently I have a MySQL query I run in PHP and when going through the results I update the original table but a simple table with 500 rows takes 30 seconds to complete:
$sqlquery = mysql_query('SELECT id, special_data FROM stats_visits WHERE processed = 0');
while($row = mysql_fetch_assoc($sqlquery)){
$stat_id = $row['id'];
// Make use of special_data field for some operations
mysql_query('UPDATE stats_visits SET processed = 1 WHERE id = ' . $stat_id);
}
Is it because I am updating the table from which I am selecting? I've solved this by doing the following but because the table might have thousands of records in future I'm unsure how well the IN will hold up:
$statids = array();
$sqlquery = mysql_query('SELECT id, special_data FROM stats_visits WHERE processed = 0');
while($row = mysql_fetch_assoc($sqlquery)){
$statids[] = $row['id'];
// Make use of special_data field for some operations
}
mysql_query('UPDATE stats_visits SET processed = 1 WHERE id IN(' . implode(',', $statids) . ')');
If all you want is to update all the records to being processed = 1 Why not resolve it with a single query?:
UPDATE `stats_visits` SET `processed` = 1 WHERE `processed` = 0;
In the first version you're hitting the database once for every single update. This is normally a bad idea. The 2nd version is hitting the database once.
If you are concerned about how this will work out in the future, perhaps create a hybrid. Batch the updates up into groups of 100 and update them in blocks.
The easiest way would be to store all of the ids which need updating as an array then implode these into the query with the IN operator.
e.g.
$processedArray= array();
while($row = mysql_fetch_assoc($sqlquery)){
$stat_id = $row['id'];
//Your processing goes here
$processedArray[] = $stat_id; //Store an id if it needs updating as processed
}
mysql_query('UPDATE stats_visits SET processed = 1 WHERE id IN ('.implode(',', $processedArray).')');
I'm afraid this is going to sound redundant. I have done my diligence, and substituted at least three ideas I've found so far, and nothing works.
The goal is to merge unique fields from two tables, but right now I can't even get identical fields from one table into another that was created as an identical table. Here is the code so far, with my comments:
$result = mysql_query("SELECT * from $db.$tbl LIMIT 50");
if($result) {
while($maindata = mysql_fetch_assoc($result)) {
$newdata = implode ("," , $maindata);
$newdata = mysql_escape_string($newdata);
$pop = "INSERT INTO $db.address_new (id,entitynum,address,city,state,zip,country,remarks)
SELECT FROM $db.address";
//This is the original code replaced by the above
//$pop = "INSERT INTO $db.address_new (id,entitynum,address,city,state,zip,country,remarks)
// VALUES ($newdata)";
mysql_query($pop);
//print_r($pop);
//Seems to give the correct output in the browser, but the table address_new remains empty. `
Thank you in advance. I really appreciate your help.
To directly insert from another table (note: if ID is auto_increment you may or may not want to insert it this way):
INSERT INTO db.address_new (id,entitynum,address,city,state,zip,country,remarks)
SELECT (id,entitynum,address,city,state,zip,country,remarks)
FROM db.address LIMIT 50
(do not put this in a loop)
If you're looking for unique values, you can do that a couple of ways. Personally, I would have a unique key on one (or a set of) the values and then just do INSERT IGNORE:
INSERT IGNORE INTO db.address_new
(id,entitynum,address,city,state,zip,country,remarks)
SELECT (id,entitynum,address,city,state,zip,country,remarks)
FROM db.address LIMIT 50
As a side note:
// use mysql_real_escape_string
mysql_escape_string($newdata);
// since you're passing this through PHP, you need to make sure to quote
// all of your values. This probably means you'll need to loop and replace this
// $newdata = implode ("," , $maindata);
// with something like:
$newdata = array();
foreach( $maindata as $column )
{
$newdata[] = "'" . mysql_real_escape_string( $column ) . "'";
}
$newdata = implode(',', $newdata);
// you're missing the columns in your select clause.
$pop = "INSERT INTO $db.address_new ".
"(id,entitynum,address,city,state,zip,country,remarks) ".
// You need to select *something*
"SELECT FROM $db.address";