I need to update id column of several tables with php uniqid() values
after running this code - all rows inside each table has the same value
how to set different value for each row ?
$arr = ['lorem', 'ipsum', 'dolor']; // table names
foreach($arr as $tb){
$st = $db-> prepare("select * from " . $tb);
$st -> execute();
$arrb = $st->fetchAll();
foreach($arrb as $elb){
$id = uniqid();
$sqb = "update " . $tb . " set id = :aid";
$stb = $db->prepare($sqb);
$stb->execute([":aid" => $id]);
}
}
As already pointed out by Amitesh, your code is setting the same uniqid() value to all rows in each table multiple times. Furthermore, you are preparing the same sql statement for each row, missing one of the important benefits of using prepared statements.
$arr = ['lorem', 'ipsum', 'dolor']; // table names
foreach($arr as $tb){
/*
* assign temporary UUID (requires CHAR(36)) to all rows if there
* is no other way of uniquely identifying the rows
*/
$db->query("UPDATE {$tb} SET id = UUID()");
$st = $db->prepare('select id from ' . $tb);
$st->execute();
$arrb = $st->fetchAll();
// prepare once per table
$sqb = "update $tb set id = :aid where id = :old_id";
$stb = $db->prepare($sqb);
foreach($arrb as $elb){
// execute once per row
$stb->execute([':aid' => uniqid(), ':old_id' => $elb['id']]);
}
}
Related
I'm trying to create a filter in DataTables, but what I found is only filtering the data in "front end" (in the datatables script). I have 10K rows in the SQL table so I think, the "front end filtering/searching" is not my best option. I need to create a filter to my SQL Query in server-side, and get back only the filtered rows (datas).
Also the search option is not good option for me because I have in tables values like 1 or 2 (boolean).
My DataTables using this method (way) of fetching datas from SQL in backend:
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value
$searchArray = array();
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " AND (emp_name LIKE :emp_name or
email LIKE :email OR
city LIKE :city ) ";
$searchArray = array(
'emp_name'=>"%$searchValue%",
'email'=>"%$searchValue%",
'city'=>"%$searchValue%"
);
}
## Total number of records without filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee ");
$stmt->execute();
$records = $stmt->fetch();
$totalRecords = $records['allcount'];
## Total number of records with filtering
$stmt = $conn->prepare("SELECT COUNT(*) AS allcount FROM employee WHERE 1 ".$searchQuery);
$stmt->execute($searchArray);
$records = $stmt->fetch();
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$stmt = $conn->prepare("SELECT * FROM employee WHERE 1 ".$searchQuery." ORDER BY ".$columnName." ".$columnSortOrder." LIMIT :limit,:offset");
// Bind values
foreach($searchArray as $key=>$search){
$stmt->bindValue(':'.$key, $search,PDO::PARAM_STR);
}
$stmt->bindValue(':limit', (int)$row, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int)$rowperpage, PDO::PARAM_INT);
$stmt->execute();
$empRecords = $stmt->fetchAll();
$data = array();
foreach($empRecords as $row){
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
In this code as you can see I have Search option, but as I said I can't use it for filtering columns with boolean values for example.
Another example what I want to do:
I have a column named by "edited" with boolean values.
How can I get those rows where the column "edited" have values 0?
I'm using MariaDB.
Thank you for your help!
You can easy write ...WHERE edited = :edited ... the value of edited should be 0 for false and 1 for true.
So in your example:
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " AND (emp_name LIKE :emp_name or
email LIKE :email OR
city LIKE :city ) AND
edited = :edited";
$searchArray = array(
'emp_name'=>"%$searchValue%",
'email'=>"%$searchValue%",
'city'=>"%$searchValue%",
'edited'=>$edited
);
}
Hello I want to run two queries in this code. The first delets a row in the mysql table and the second reorders the id value to the right sequence.
if(isset($_POST["image_id"]))
{
$file_path = 'files/' . $_POST["image_name"];
if(unlink($file_path))
{
$count= 0;
$count++;
$query1 = "DELETE FROM tbl_image WHERE image_id = '".$_POST["image_id"]."'";
$query2 = "UPDATE 'tbl_image' SET 'image_id' = '$count' " ;
$statement = $connect->prepare($query1, $query2);
$statement->execute();
}
}
currently I have two pieces of data being stored in a sql db and then pulled into my website. What I want though is the two pieces of data being stored to be separated instead of totaled together.
So i setup my DB like so:
DROP TABLE IF EXISTS totals;
CREATE TABLE totals (
id int(11) NOT NULL AUTO_INCREMENT,
total float NOT NULL,
PRIMARY KEY (id)
) ;
INSERT INTO totals VALUES (1, 0);
And the PHP I'm using:
$api = array();
$api[] = 'http://api.jo.je/justgiving/data/myuserpage';
$api[] = 'http://api.jo.je/justgiving/data/myuserpage2';
$total = 0;
foreach($api as $data) {
$open = file_get_contents($data);
$feed = json_decode($open);
if(is_object($feed)) {
$total = $total + $feed->donations_total;
}
}
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass); // new data
$id = 1;
// query
$sql = "SELECT total
from totals
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($id));
$data = $q->fetch();
$total = $data['total'];
Being a noobie at this, I just need some help storing two seperate pieces of data instead of one.
I think you simply want two separate columns in the table:
CREATE TABLE totals (
id int(11) NOT NULL AUTO_INCREMENT,
total1 float NOT NULL,
total2 float NOT NULL,
PRIMARY KEY (id)
) ;
$api = array(
'total1' => 'http://api.jo.je/justgiving/data/myuserpage',
'total2' => 'http://api.jo.je/justgiving/data/myuserpage2',
);
// The saving part is missing from your code, but it should be something like
$sql = "UPDATE totals SET {$source}=? WHERE id=?";$q = $conn->prepare($sql);
$query = $conn->prepare($sql);
// Note: the above assumes that the "id" already exists. Otherwise
// you need an "UPSERT" (UPdate or inSERT) that will insert a new value or update
// it if it already exists. Find more # this answer:
// https://stackoverflow.com/questions/15383852/sql-if-exists-update-else-insert-into
/*
* Instead of adding up the two API calls' results, we store them separately
*
* Of course the value of "id" here must be the same as in the second page, or
* what you will retrieve will NOT be what you have stored!
*/
foreach($api as $column => $source) {
$data = file_get_contents($source);
$feed = json_decode($data);
if (is_object($feed)) {
$value = $feed->donations_total;
$query->execute(array($value, $id));
}
}
Now in the second page
// query
$sql = "SELECT total1, total2 from totals WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($id));
$data = $q->fetch();
$total1 = $data['total1'];
$total2 = $data['total2'];
(This is the link to the answer referred above).
I have
$result = "";
if(someCondition)
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
else
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
$result could have 0 -> infinity rows returned
Table 1 and Table 2 have different amounts of columns with different names
I want to write 1 generic loop after the above else that will just print out all of the rows. Preferably 1 per line or deliminated.
To clarify, one of the two query calls will fill the $results variable with rows.
I wont know which one fills it at run time so I want to just do a print all contents to screen. Is there a method that does this? is there a fast loop that iterates through all of the rows without explicitly saying the column names?
bored enough to answer:
$result = "";
if(someCondition){
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
}else{
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
}
while ($row = mysql_fetch_array($result)) ) {
foreach($row as $key => $var)
{
echo $key . ' = ' . $var . '<br />';
}
}
Hi I made a query to a table below and when I tried to get the value in each column , it returns the same value from the first column for all the other columns.
To elaborate
In my database table I have the following:
owner_id = 21
pet_id = 1
name = fluffy
color = green
type = dog
sub_type = boxer
location = LA
however whenever I try to access one column, say the name column, it returns 21 which is the
value in the owner_id column corresponding to that pet_id. I am not sure why this is
happening.
$query = sprintf("SELECT * FROM `petAttributes` where pet_id ='%d'",$p_id);
$result = performQuery($query);
$owner_id = stripslashes(mysql_result($result,"owner_id"));
$pet_id = stripslashes(mysql_result($result,"pet_id"));
$name = stripslashes(mysql_result($result,"name"));
$color = stripslashes(mysql_result($result,"color"));
$type = stripslashes(mysql_result($result,"type"));
$sub_type = stripslashes(mysql_result($result,"sub_type"));
$loc = stripslashes(mysql_result($result,"location"));
Information on my environment
PHP Version 5.2.14
MYSQL version 5.0.67
I believe that if you use mysql_result you also have to specify the row index number (row 0 in your case?), before you specify the column.
$name = stripslashes(mysql_result($result, 0, "name"));
refering to http://php.net/manual/en/function.mysql-result.php mysql_result has it's parameters like this: mysql_result($result,$rownumber,$fieldname or $fieldnumber)
this should workd:
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
$owner_id = stripslashes(mysql_result($result,0,"owner_id"));
$pet_id = stripslashes(mysql_result($result,0,"pet_id"));
$name = stripslashes(mysql_result($result,0,"name"));
$color = stripslashes(mysql_result($result,0,"color"));
$type = stripslashes(mysql_result($result,0,"type"));
$sub_type = stripslashes(mysql_result($result,0,"sub_type"));
$loc = stripslashes(mysql_result($result,0,"location"));
BTW mysql_result is getting very inefficient if you take more than one row.
Then you should use mysql_fetch_row, mysql_fetch_array or mysql_fetch_assoc
Also you can;
for only first row
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
$row = mysql_fetch_array($result);
extract($row);
or all returned rows;
$query = sprintf("SELECT * FROM petAttributes where pet_id ='%d'",$p_id);
$result = performQuery($query);
while($row = mysql_fetch_array($result))
{
foreach ($row as $value) echo $value."<br>";
}