How to create an array data from database?
I want to show random data by using array_rand.
If we create by manual is like this.
$a = ['http://php.net/', 'http://google.com/', 'http://bbc.co.uk/'];
Then call it:
echo $a[array_rand($a)];
I try to creat same like that, but fail. Here's what I try:
Data from database:
$query2 = $db->prepare ("SELECT idc FROM content ORDER BY RAND() LIMIT 5");
$query2->execute();
while ($value2 = $query2->fetch()) {
$data_idc[] = $value2['idc'];
}
Then I try to create a same code like code above:
$bank_idc_1 = [ $string_result = "'". implode("', '", $data_idc) . "'" ];
Then I call it:
echo $bank_idc_1[array_rand($bank_idc_1)];
But I get error.
There is no need of this line
$bank_idc_1 = [ $string_result = "'". implode("', '", $data_idc) . "'" ];
Directly go for:-
echo $data_idc[array_rand($data_idc)];
Description:- Through while() loop you are already getting an array so you need to apply array_rand() directly on it.
Related
In one file i have something like this:
$result = mysqli_query($con, "SELECT * FROM users WHERE id_province = '".$province_id."' AND id_city = '".$city_id."' AND age >= '".$age1."' AND
age <= '".$age2."' AND id_rank = '".$rank_id."' AND id_position = '".$position_id."';");
while ($row = mysql_fetch_array($result)) {
$array[] = $row;
}
And I want to use $array in another php file. How can I do it?
You can use SESSIONS
session_start();
$result = mysqli_query($con, "SELECT * FROM users WHERE id_province = '" . $province_id . "' AND id_city = '" . $city_id . "' AND age >= '" . $age1 . "' AND
age <= '" . $age2 . "' AND id_rank = '" . $rank_id . "' AND id_position = '" . $position_id . "';");
while ($row = mysql_fetch_array($result)) {
$array[] = $row;
}
$_SESSION['array'] = $array;
and in second file you can use code below
#session_start();
$array = $_SESSION['array'];
When trying to pass between multiple files, you could use classes instead of scripts. This helps maintain the code better.
Let's say the second file was SecondFile.class. I could instantiate it and then pass the array as a parameter.
$secondFile = new SecondFile;
$secondFile->someClassMethod($array);
Or, if you don't need to use the second file for anything else, use a shorter syntax:
(new SecondFile)->someClassMethod($array);
So... "export" is the wrong term for this, what you are looking at is variable scope
In the simplest terms - something declared outside a function is "global" and something declared within a function is private to that
You want to pass an array from one file to another? If you have 3 files (main, include_num1 and include_num2), this is simple;
Main;
<?php
require_once 'include_num1.php';
require_once 'include_num2.php';
?>
include_num1;
<?php
$myarray = array("a", "b", "c")
?>
include_num2;
<?php
var_dump($myarray);
?>
This will produce something like;
myarray = (array)
string 0 : a(1)
string 1 : b(1)
string 2 : c(1)
This is because in this example, the array is declared in the global scope, if you did the require's the other way around - this would error as at time of the var dump, $myarray does not exist
You can skip out the "main" by just including the include_num2 from the include_num1
If you want to use a global variable inside a function, declare the function as normal, and use the global available;
<?php
$myvar = "A variable";
function myFunction()
{
if (isset($myvar)) print $myvar; // Will do nothing
global $myvar;
if (isset($myvar)) print $myvar; // Will Print "A variable"
}
?>
You can save your array in the database, file, cookie, session....
It depends of what you want to do versus the necessary security level.
The simplest way would be:
//At the top of your page
#session_start();
//This line goes after you get all data you want inside your array
$_SESSION['mySession'] = $array;
And in the other page:
//At the top of your page
#session_start();
//To recover you array:
$array = $_SESSION['mySession'];
Not the best option, but it works.
In the form, none of the inputs are mandatory. So, I want to have a dynamic "where" clause inside the wpdb query.
Presently this is the query:
$data = $wpdb->get_results($wpdb->prepare("SELECT * FROM
`wp_gj73yj2g8h_hills_school_data` where
`school_zipcode` = %d AND `school_type` = %s AND `school_rating` = %s
;",$selectedZip,$selectedType,$selectedRating));
if a user enters only school_zipcode then the where clause should have only "school_zipcode" column.
Same way for other combinations.
I would not make things complicated with dynamic where clauses... I would write PHP code which creates the query. For example...
NOTE!! THIS CODE IS NOT TESTED ON SERVER, IT'S JUST AN IDEA HOW TO SOLVE THE PROBLEM!
<?php
$where_query = array();
// Make sure to escape $_POST
if (!empty($_POST['school_zipcode')) {
$where_query[] = "school_zipcode='" . $_POST['school_zipcode'] . "'";
}
// Make sure to escape $_POST
if (!empty($_POST['school_type')) {
$where_query[] = "school_type='" . $_POST['school_type'] . "'";
}
// Should result in WHERE school_zipcode='123' AND school_type='text'
$where_query_text = " WHERE " . implode(' AND ', $where_query);
$data = $wpdb->get_results($wpdb->prepare("SELECT * FROM `wp_gj73yj2g8h_hills_school_data` " . $where_query_text . ";"));
I have the following code (SQL-query tested in phpMyAdmin and seems to work) that fetch data from selected columns:
$ids = isset($_REQUEST['id']) ? $_REQUEST['id'] : array();
if (is_array($ids)) $ids = implode(',', $ids);
if (!empty($ids)) {
$sql = "SELECT upload, upload2, upload3, upload4, upload5 FROM wp_site_table WHERE cid IN($ids) ORDER BY FIELD(cid, $ids)";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ) { ... } }
The problem I have is that I want to output all fields from selected cid.
This code will only display the first cid result.
echo $result->upload;
Let's say $ids contain cid 1, 4 and 7 I'd like to output upload, upload2, upload4, upload5 from all those specific rows. How? Use an array in some way?
kind regards
Johan
If you want to echo all the fields, just do it:
echo $result->upload . '<br>' . $result->upload2 . '<br>' . $result->upload3 .
'<br>' . $result->upload4 . '<br>' . $result->upload5;
You should perhaps consider redesigning your database so you don't have repeated fields in each row. It would be better to have another table where each upload is in a row of its own, so there's no hard-coded limit on the number of these values. Then you can use a JOIN query to get all the uploads, and they'll be in an array.
With '$wpdb->get_results' output defaults to OBJECT type. Try using pre defined constant : ARRAY_A , it will result the output as an associative array.
$sql = "SELECT upload, upload2, upload3, upload4, upload5 FROM wp_site_table WHERE cid IN($ids) ORDER BY FIELD(cid, $ids)";
$results = $wpdb->get_results($sql, ARRAY_A) or die(mysql_error());
To access, simply use :
foreach( $results as $result ){
echo $result['upload'];
}
I am trying to be lazy (or smart): I have 7 checkboxes which correlate with 7 columns in a MySQL table.
The checkboxes are posted in an array:
$can = $_POST['can'];
I've created the following loop to dump the variables for the MySQL insert:
for($i=1;$i<8;$i++){
if($can[$i] == "on"){
${"jto_can".$i} = 'Y';
}
else{
${"jto_can".$i} = 'N';
}
}
print_r($jto_can1.$jto_can2.$jto_can3.$jto_can4.$jto_can5.$jto_can6.$jto_can7);
This correctly outputs:
YYNYYYY
However, when I attempt to use those variables in my MySQL update, it doesn't accept the changes.
mysqli_query($db, "UPDATE jto SET jto_can1 = '$jto_can1', jto_can2 = '$jto_can2', jto_can3 = '$jto_can3', jto_can4 = '$jto_can4', jto_can5 = '$jto_can5', jto_can6 = '$jto_can6', jto_can7 = '$jto_can7' WHERE jto_id = '$id'")or die(mysqli_error($db));
Can anyone explain why the print_r displays the variables whereas MySQL update does not?
Stick with the array, and form the query dynamically:
$sql = 'UPDATE jto SET ';
$cols = array();
foreach( range( 1, 7) as $i) {
$value = $_POST['can'][$i] == 'on' ? 'Y' : 'N'; // Error check here, $_POST['can'] might not exist or be an array
$cols[] = 'jto_can' . $i . ' = "' . $value . '"';
}
$sql .= implode( ', ', $cols) . ' WHERE jto_id = "' . $id . '"';
Now do a var_dump( $sql); to see your new SQL statement.
this is not a mysql problem. mysql will only see what you put into that string. e.g. dump out the query string BEFORE you do mysql_query. I'm guessing you're doing this query somewhere else and have run into scoping problems. And yes, this is lazy. No it's not "smart". you're just making MORE work for yourself. What's wrong with doing
INSERT ... VALUES jto_can1=$can[0], jto_can2=$can[1], etc...
I have a select query followed by a an update query inside a foreach loop.
I can get the data from the select and I use it as json to draw a chart, but for the other table that should be updated with the same data from select, the specified filed become 0 sometimes 1 or 2 !!
I tried to use a select for update and it OK (update .... (select ....)) but inside foreach it doesn't work.
I tried also to use other columns but the same result, always I get 0.
Any idea please ?
Many thanks in advance
this is my code
public function actionGetSensorsDataLive($beamId) {
header('Content-Type: application/json; charset="UTF-8"');
$sensorsIds = Sensor::model()->findAllBySql('SELECT sensor_id FROM sensor where
node_id="' . $beamId . '" and sensor_name = "I" ;');
foreach ($sensorsIds as $s) {
$sResult = array();
$modelSensor = SensorInfo2::model()->findBySql('SELECT * FROM information_sensor
where sensor_id= "' . $s['sensor_id'] . '"');
$sResult = array(($modelSensor->information_sensor_time),
($modelSensor->information_sensor_value));
/////////////// update////////////////
// for every information_sensor_time that I get from the previous query
// I want
// to update a row in another table //
foreach ($modelSensor as $up) {
$connection = yii::app()->db;
$sql = 'UPDATE last_point SET last_point_time = "' .
$up['information_sensor_time'] . '"
WHERE sensor_id= "' . $s['sensor_id'] . '" ';
$command = $connection->createCommand($sql);
$command->execute();
}
/////update end///////
}
echo json_encode($sResult);
Yii::app()->end();
}
$sensorsIds=Sensor::model()->findAllBySql('SELECT sensor_id FROM lead where
node_id="'.$beamId.'" and sensor_name = "I" ;' );
Remove ;
$sensorsIds=Sensor::model()->findAllBySql('SELECT sensor_id FROM lead where
node_id="'.$beamId.'" and sensor_name = "I"' );
Now try this.
You are using findBySql()` which only returns one record and then doing a foreach on tha makes no sense. so cheng the line
$modelSensor = SensorInfo2::model()->findBySql('SELECT * FROM information_sensor
where sensor_id= "' . $s['sensor_id'] . '"');
to
$modelSensor = SensorInfo2::model()->findAllBySql('SELECT * FROM information_sensor
where sensor_id= "' . $s['sensor_id'] . '"');
And you shoud use querybuilder which is far secure as suggested by Alex
finally I used this code
foreach ($sensors as $sensor) {
$lastPointId = 1;
$lastPoint = LastPoint::model()->findByPk($lastPointId);
$lastPoint->last_point_info = $sensor->information_time;
if ( ! $lastPoint->save()) {
throw new CException('Unable to save last point.');
}
}
Thanks for all