I am getting data back from a database query but I need to update an array.
sub get_query_data{
my ($self, $user_id) = #_;
my $sql_query = "Select * from table";
my ( $returndata ) = $self->_exec_and_fetch_all( $sql );
for ( #$returndata ) {
push( #$_, 'replace me' );
}
return $returndata;
}
How do I replace the third element when I am looping through the data?
There is data coming back from the query but he above is not working.
If $self->_exec_and_fetch_all can return undef,
my $rows = $self->_exec_and_fetch_all($sql);
if ($rows) {
for my $row (#$rows) {
$row->[2] = 'replaceme';
}
}
return $rows;
Otherwise,
my $rows = $self->_exec_and_fetch_all($sql);
for my $row (#$rows) {
$row->[2] = 'replaceme';
}
return $rows;
or
my $rows = $self->_exec_and_fetch_all($sql);
$_->[2] = 'replaceme' for #$rows;
return $rows;
Related
Here I have a translator that must get data from mysql and then show them like a $_name = array ($_en, $_ru, $_ua) and then I want to choose data by cases [0] or [1] or [3]
I need to show mysql result an array
I've already try this it but it doesn't work
<?php
$result1 = mysql_query("SELECT t_name, t_ru, t_ua, t_en FROM transl_db ");
while ($row = mysql_fetch_array($result1)) {
t_name = array ('t_ru', 't_ua', 't_en' )
}
?>
$result = mysql_query("SELECT t_name, t_ru, t_ua, t_en FROM transl_db ");
while ($row = mysql_fetch_array($result))
$t_names[] = $row;
Try
$result1 = mysql_query("SELECT t_name, t_ru, t_ua, t_en FROM transl_db ");
while ($row = mysql_fetch_array($result1)) {
$t_names[] = array ('t_ru'=>$row['t_ru'],'t_ua'=> $row['t_ua'],'t_en'=>$row['t_en'] );
}
or
while ($row = mysql_fetch_array($result1)) {
$t_names[] = $row;
}
now data available on $t_names
I tried it but I have to get also $t_name from mysql and then have it like an array
$result1 = mysql_query("SELECT t_name, t_ru, t_ua, t_en FROM transl_db ");
while ($row = mysql_fetch_array($result1)) {
('t_name'=>$row['t_name'] )= array ('t_ru'=>$row['t_ru'],'t_ua'=>
$row['t_ua'],'t_en'=>$row['t_en'] );
};
?>
I am currently having problem getting the number of rows in my code. here's my code:
$app->get('/banana/:state', function($state) use ($app){
$db = new DbOperation();
$today = date("j-M-Y");
if($state == "Indoor"){
$result = $db->getAllbananaindoor($today);
$response = array();
$response['messages'] = array();
$row = $result->fetch_assoc();
if($row > 3){
$temp = array();
$temp['text'] = 'Yes, you can plant banana seeds today indoors.';
array_push($response['messages'],$temp);
}
else {
$temp = array();
$temp['text'] = 'Nope. Today is not a good time to plant banana seeds indoors.';
array_push($response['messages'],$temp);
}
echoResponse(200,$response);
}
}
public function getAllbananaindoor($today){
$stmt = $this->con->prepare("SELECT * FROM garden WHERE humid >? AND time=? AND temp BETWEEN ? AND ?");
$hum = '50';
$one = '19';
$two = '24';
$stmt->bind_param("iiii",$hum, $today, $one, $two);
$stmt->execute();
$students = $stmt->get_result();
$stmt->close();
return $students;
}
In this I get the database data from a function getAllBananaindoor() which returns the result instead i want it return the number of rows and finally check whether $row is greater than 3 and then work on that. how can I do that? please help.
The MySQLi Result object has num_rows property defined.
$students = $stmt->get_result();
return $students->num_rows; // will return the number of rows
I'm fetching data from mysql like ...
$query = "SELECT legal_country, count(*) FROM accounts GROUP BY legal_country ORDER BY count(*) DESC";
$result = mysql_query( $query );
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
return json_encode( $data );
Current result is:
[{"legal_country":"US","count(*)":"107865"},{"legal_country":"DE","count(*)":"44711"},{"legal_country":"SL","count(*)":"1"}]
Yet, my goal is to have the json string like:
{"map": "worldLow", "areas": [{"id": "US","value": "107865"},{"id": "DE","value": "44711"},{"id": "SL","value": "1"}]}
How can I add {"map": "worldLow", "areas": .... } prior to the array and how can I exchange the labels legal_country -> id and count(*) -> value ??
In addition, this is a working example with 'echo' ... yet I need it with the 'return' function ...
$prefix = '';
echo '{"map": "worldLow", "areas": [';
while ( $row = mysql_fetch_assoc( $result ) ) {
echo $prefix . " {\n";
echo ' "id": "' . $row['legal_country'] . '",' . "\n";
echo ' "value": "' . $row['count(*)'] . '"' . "\n";
echo " }";
$prefix = ",\n";
}
echo "\n]}";
The working example with echo looks like this:
{"map": "worldLow", "areas": [ {
"id": "US",
"value": "107865"
},
{
"id": "DE",
"value": "44711"
},
{
"id": "SL",
"value": "1"
}
]}
Create an array with the result according to your requirement.
$query = "SELECT legal_country AS `id`, count(*) AS `value`
FROM accounts
GROUP BY legal_country
ORDER BY count(*) DESC";
$dataArr = $areasArr = array();
if ($result = mysql_query( $query )) {
while ( $row = mysql_fetch_assoc( $result ) ) {
$areasArr[] = $row;
}
$dataArr = array(
"map" => "worldLow",
"areas" => $areasArr
);
}
return json_encode( $dataArr, true );
Also use mysqli_* functions instead of mysql_*
You have to change slightly your query and $data before using json_encode
$query = "SELECT legal_country as `id`, count(*) as `value` FROM accounts GROUP BY legal_country ORDER BY count(*) DESC";
$result = mysql_query( $query );
$json= array();
$area = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$area[] = $row;
}
$data = array(
'map' => 'worldlow',
'area' => $area,
);
return json_encode( $data );
I like to write a csv import / update to my Mysql database, but it isnt working. I get no error messages.
Can anybody help me to find the error or whats wrong with my script please.
// set local variables
$connect = mysql_connect("localhost","root","") or die('Could not connect: ' . mysql_error());
$handle = fopen("imptest.csv", "r");
// connect to mysql and select database or exit
mysql_select_db("shoptest1", $connect);
while($data = fgetcsv($handle, 30000, ';')) //Jede Zeile durchgehen
{
$Product_ID=$data[0];
$field=$data[1];
$query = 'SELECT Product_ID FROM testprod';
if (!$result = mysql_query($query)) {
continue;
} if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// entry exists update
$query = "UPDATE ps_product_lang SET custom_field ='$field' WHERE id_product = '$Product_ID'";
mysql_query($query);
if (mysql_affected_rows() <= 0) {
echo "kein update";
// no rows where affected by update query
}
} else {
echo "kein eintrag";
// entry doesn't exist continue or insert...
}
mysql_free_result($result);
}
fclose($handle);
mysql_close($connect);
?>
The queries you are performing:
SELECT Product_ID FROM testprod
UPDATE nl_product_lang SET custom_field = ? WHERE Product_ID = ?
are suitable to detect whether a product exists and then either UPDATE or INSERT. For only an UPDATE, the SELECT doesn't matter, as there won't be an entry WHERE Product_ID NOT IN (SELECT Product_ID FROM testprod) - if you have a foreign key.
Here's an example of how to do this using PDO.
list( $SQLDSN, $SQLUSER, $SQLPASS ) = [ 'mysql:dbname=shoptest1', 'root', '' ];
$db = new PDO( $SQLDSN, $SQLUSER, $SQLPASS, [
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
] );
$ids = $db->query( "SELECT Product_ID from testprod" )->fetchAll( \PDO::FETCH_COLUMN, 0 );
while ( list( $Product_ID, $field ) = fgetcsv(...) )
if ( in_array( $Product_ID, $ids ) )
query( $db, "UPDATE ps_product_lang SET custom_field = ? WHERE Product_ID = ?",
[ $field, $Product_ID ]
);
else
trigger_warning( "unknown product $Product_ID" );
function query( $db, $sql, $args = null ) {
$sth = $db->prepare( $sql );
$sth->execute( $sql );
return $sth;
}
Is it possible to predict the operations that follow a DELETE CASCADE automatically? In my software I would like to give the user a warning with details about the data that would be deleted then.
You can make a copy of the database and put triggers on the after delete
DELIMITER $$
CREATE TRIGGER ad_table1_each AFTER DELETE ON table1 FOR EACH ROW
BEGIN
INSERT INTO log VALUES (null /*autoinc id*/
, 'table1' /*tablename*/
, old.id /*tableid*/
, concat_ws(',',old.field1,old.field2 /*CSV's of fields*/
, NOW() /*timestamp*/
, 'delete'); /*what action*/
REPLACE INTO restore_table1 VALUES (old.id,
, old.field1
, old.field2
, ... );
END $$
DELIMITER ;
The log table is just a table with the following fields:
id integer autoincrement primary key
tablename varchar(45)
table_id integer
fields varchar(6000)
delete_time timestamp
action enum('insert','update','delete')
If you do a SELECT #last_id:= max(id) FROM log before the delete cascade on the copy.
Then you can do a SELECT * FROM log WHERE id > #last_id
and get all the rows that will be deleted in the cascade.
After that you can use the restore_table1 to recreate the rows that were deleted in the cascade in the copy database.
I think you could use Johan's trigger solution in combination with a transaction that you roll back. This avoids both the need for a second database and for the manual restore of the deleted entries.
add the trigger and the log table
for each attempted deletion start a transaction and delete the entries
present the information from the log to your user for approval
if the user agrees commit the transaction, otherwise rollback
I wrote a very quick hack that does exactly what you need in PHP, since I wanted to do the exact same thing and haven't found any resources for that online.
It might be too late for you, but it may help others.
function get_referencing_foreign_keys ($database, $table) {
$query = 'SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = "'.$database.'" AND REFERENCED_TABLE_NAME = '.esc($table);
$result = rquery($query);
$foreign_keys = array();
while ($row = mysql_fetch_row($result)) {
$foreign_keys[] = array('database' => $row[0], 'table' => $row[1], 'column' => $row[2], 'reference_column' => $row[3]);
}
return $foreign_keys;
}
function get_foreign_key_deleted_data_html ($database, $table, $where) {
$data = get_foreign_key_deleted_data ($database, $table, $where);
$html = '';
foreach ($data as $key => $this_data) {
$html .= "<h2>$key</h2>\n";
$html .= "<table>\n";
$i = 0;
foreach ($this_data as $value) {
if($i == 0) {
$html .= "\t<tr>\n";
foreach ($value as $column => $column_value) {
$html .= "\t\t<th>".htmlentities($column)."</th>\n";
}
$html .= "\t</tr>\n";
}
$html .= "\t<tr>\n";
foreach ($value as $column => $column_value) {
$html .= "\t\t<td>".htmlentities($column_value)."</td>\n";
}
$html .= "\t</tr>\n";
$i++;
}
$html .= "</table>\n";
}
return $html;
}
function get_foreign_key_deleted_data ($database, $table, $where) {
$GLOBALS['get_data_that_would_be_deleted'] = array();
$data = get_data_that_would_be_deleted($database, $table, $where);
$GLOBALS['get_data_that_would_be_deleted'] = array();
return $data;
}
function get_data_that_would_be_deleted ($database, $table, $where, $recursion = 100) {
if($recursion <= 0) {
die("Deep recursion!");
}
if($recursion == 100) {
$GLOBALS['get_data_that_would_be_deleted'] = array();
}
if($table) {
if(is_array($where)) {
$foreign_keys = get_referencing_foreign_keys($database, $table);
$data = array();
$query = 'SELECT * FROM `'.$table.'`';
if(count($where)) {
$query .= ' WHERE 1';
foreach ($where as $name => $value) {
$query .= " AND `$name` = ".esc($value);
}
}
$result = rquery($query);
$to_check = array();
while ($row = mysql_fetch_row($result)) {
$new_row = array();
$i = 0;
foreach ($row as $this_row) {
$field_info = mysql_fetch_field($result, $i);
$new_row[$field_info->name] = $this_row;
foreach ($foreign_keys as $this_foreign_key) {
if($this_foreign_key['reference_column'] == $field_info->name) {
$to_check[] = array('value' => $this_row, 'foreign_key' => array('table' => $this_foreign_key['table'], 'column' => $this_foreign_key['column'], 'database' => $this_foreign_key['database']));
}
}
$i++;
}
$GLOBALS['get_data_that_would_be_deleted'][$table][] = $new_row;
}
foreach ($to_check as $this_to_check) {
if(isset($this_to_check['value']) && !is_null($this_to_check['value'])) {
get_data_that_would_be_deleted($database, $this_to_check['foreign_key']['table'], array($this_to_check['foreign_key']['column'] => $this_to_check['value']), $recursion - 1);;
}
}
$data = $GLOBALS['get_data_that_would_be_deleted'];
return $data;
} else {
die("\$where needs to be an array with column_name => value pairs");
}
} else {
die("\$table was not defined!");
}
}
Imagine I have a table called "table" in the database "db" and I want to delete the one with the id 180, then I'd call:
print(get_foreign_key_deleted_data_html('db', 'table', array('id' => 180)));
and it prints a full table with all the rows and all the values that would be deleted.
But as I've said, this is a very, very quick and dirty hack. I'd be glad for any bug-report (and there surely are a lot of them!).