I have a database and a table in it called 'data'. There are 2 rows in this table.
I want to select all the data in there with php. Here is the code:
$FoodNamedata = mysqli_query($vb,"select * from data");
$FoodName = mysqli_fetch_array($FoodNamedata, MYSQL_NUM);
print_r($FoodName);
With this code it only selects the first ID in the table and prints it.
Use this code:
$FoodNamedata = mysqli_query($vb,"select * from data");
while (($FoodName = mysqli_fetch_array($FoodNamedata, MYSQL_NUM))!==null) {
print_r($FoodName);
}
You must use it in a loop, if you want a single function here is some I made now:
<?php
function get_data($link,$query) {
$res = mysqli_query($link,$query);
$return = array();
while($rec = mysqli_fetch_array($res,MYSQL_NUM)) {
$return[] = $rec;
}
return $return;
}
?>
Then you just use
$foodname = get_data($vb,"select * from data");
Related
I want to make a function in PHP to return a list of mysql results. But i want to enter my own tekst also.
When i echo i get the results but i want to return the value.
function Get() {
$sql = mysqli_query($link, "SELECT * FROM blabla");
$value4 = 'certain';
while($approw = mysqli_fetch_array($sql)){
$value= 'Fun '. $approw['value1'].' '.$approw['value2'].' '.$approw['value3'].'percent '.$value4.'<br />' ;
}
return $value.' Powered by Hisenseb';
}
?>
In the while the results can change anytime
How can i do this? Can anyone tell me how? Thanks in advance.
Pass a mysqli::connect() object to the Get() function as an argument, and for example, select a array as the return value where you store the result set from the sql query and the text you want. Try it:
function Get(mysqli $connect)
{
$ret = [];
$value4 = 'certain';
if ($res = $connect->query("SELECT * FROM blabla")) {
$row = $res->fetch_all(MYSQLI_ASSOC);
$ret['mytext'] = 'Fun '. $row['value1'].' '.$row['value2'].' '.$row['value3'].'percent '.$value4.'<br />' ;
$ret['result-set'] = $row;
}
$connect->close();
return count($ret) > 0 ? $ret : false;
}
Now just call the function:
$conn = new mysqli("localhost","user","password","database");
$result = Get($conn);
$sql = $result['result-set'];
$mytext = $result['mytext'];
// You can then get the data from the sql table using the column names of your table:
$column1 = $sql['column1']; //Now in $column1 you have the value from the SQL table from column column1.
I am new with php, I try to call the following function in order to populate an array of previously inserted data in mysql, but I get null.
function GetBusiness($con, $email)
{
$query = "SELECT * from Business WHERE B_EMAIL ='".$email."'";
$res = mysqli_query($con,$query);
$result_arr = array();
while($row = mysqli_fetch_array($res))
{
$result_arr[] = $row;
}
return $result_arr;
}
and then I try to construct my json object as..
$result_business = array();
$result_business = GetBusiness($con, $email);
$json['result'] = "Success";
$json['message'] = "Successfully registered the Business";
$json["uid"] = $result_business["id"];
$json["business"]["name"] = $result_business["name"];
$json["business"]["email"] = $result_business["email"];
but for even if the data are inserted successfully the part of $result_business is null, why I get null? I my $query typed wrong?
thank you
The problem is, your function GetBusiness returns a multi-dimensionnal array, you can use this one instead :
function GetBusiness($con, $email)
{
$query = "SELECT * from Business WHERE B_EMAIL ='".$email."'";
$res = mysqli_query($con,$query);
return mysqli_fetch_array($res);
}
Also, you must use the MySQL columns that you selected to access the data of the rowset. Something like
$json["uid"] = $result_business["B_ID"];
$json["business"]["name"] = $result_business["B_NAME"];
i have a trouble, when select table user in yii2 , data no show up
$sqlGetuser = "select * from user ";
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
foreach($sqlquery as $row){
// echo $row;
// echo "saya";
echo $row['username'];
}
The error is in this line:
$sqlquery = Yii::$app->db->createCommand($sqlGetuser)->query();
query() returns yii\db\DataReader. To return array of rows use queryAll():
$rows = Yii::$app->db->createCommand($sqlGetuser)->queryAll();
If you want to use query(), you need to read data differently:
$command = $connection->createCommand('SELECT * FROM "user"');
$reader = $command->query();
while ($row = $reader->read()) {
$rows[] = $row;
}
// equivalent to:
foreach ($reader as $row) {
$rows[] = $row;
}
// equivalent to:
$rows = $reader->readAll();
See more in official docs.
Also quote table name as adviced since it's reserved word.
So the task is:
Do a query like Select * from table.
Take some cell value
Insert this value to a new query.
What do I have so far:
$Conn = odbc_connect("...");
$Result = odbc_exec("Select ...");
while($r = odbc_fetch_array($Result))
// showing result in a table
Here it looks like I should use the r array and insert data like
$var = r['some_field'];
$query = 'Select * from table where some_field = {$var}";
But how can I fill this array with values and how to make it available out of while loop?
Here I'm using odbc, but it doesn't matter, I need the algorithm. Thanks.
The whole code looks like:
<?php
$data = array();
$state = 'false';
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
$data = array();
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
$state = 'true';
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//I need to use $data HERE. Doesn't work
// $state = 'false' here...
}
?>
Define array outside while loop
$data = array();//defining
while($r = odbc_fetch_array($Result))
use array_push() inside while loop
array_push($data, $r['some_field']);
then try to print array of complete data outside loop
print_r($data);
Updates
Place $data = array(); at the top of first IF statement. Try this code:
$data = array();//at top
if($_REQUEST['user_action']=='')
{
$Conn = odbc_connect("...");
if($_REQUEST['name']!='')
{
$Result = odbc_exec($Conn, "select ...");
//Showing result table
while($r = odbc_fetch_array(Result))
{
array_push($data, $r['cardgroup']);
}
// print_r($data); WORKS;
}
}
if ($_REQUEST['user_action'] == 'action1')
{
//print_r($data) works here also
}
try something like this to store data in array
$allrows = array();
while($r = odbc_fetch_array( $result )){
$allrows[] = $r;
}
use foreach loop to print or use as per your choice
foreach($allrows as $singlerow) {
//use it as you want, for insert/update or print all key value like this
foreach($singlerow as $key => $value) {
//echo $key . '=='. $value;
}
}
You can try this as i understand your query hope this is your answer
$arr ='';
while($row = odbc_fetch_array($Result)) {
$arr .= '\''.$row['some_field'].'\',';
}
$arr = trim($arr, ",");
$query = "SELECT * from table where some_field IN ($arr)";
Your all task can be completed in single query
INSERT INTO table2 (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM table1
I'm a newbie to PHP and I'm just trying the very basics of MVC. Everything is going good but I have a problem while fetching data from MySQL and populating a HTML table with it.
The problem is that my code is just returning one row of the table (there are three rows in that table).
I have tried many things and right now I'm using arrays for storing the data and passing to controller and then to the view.
Query class file having a function for getting data and name queryDB:
public function getdata(){
$connectObj=new dbConnection();
//its a connection class where mysql connection has been made
if(!$connectObj->connectDB()){
echo "Error in mysql: ".mysql_error();
return false;
}
else{
$query = "select * from tbl_cartypes";
$result = mysql_query($query) or die("Error: ".mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[0] = $row['car_id'];
$data[1] = $row['car_name'];
$data[2] = $row['car_model'];
$data[3] = $row['car_type'];
$data[4] = $row['car_price'];
}
return $data;
}
$connectObj->closeDB();
}
The controller class where the controller of this query is name carController.php:
public function getAllData(){
$runQuery = new queryDB();
$array = array();
$array = $runQuery->getTickets($userid);
return $array;
}
And the final view where I'm just echoing my data:
include "$path/controllers/carController.php";
$ticket = new carController();
$array = array();
$array = $ticket->getdata();
for($i=0;$i<count($array);$i++){
echo $array[$i]."<br />";
}
Output of this code is without error, but the problem is that it's just fetching one row of the table whereas there are three rows.
So any one can help me with this?
It's fetching all rows, but you're saving all the data to the same place ($data[0] through $data[5]), so all but the last row is getting overwritten.
This might work better:
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
Using PDO and what other people have posted try using this
public function getdata(){
$connectObj=new dbConnection();
//its a connection class where mysql connection has been made
if(!$connectObj->connectDB()){
echo "Error in mysql: ".mysql_error();
return false;
}
else{
$query = 'select * from tbl_cartypes';
$result = $connectObj->query($query);
$data = array()
foreach ($result as $row){
array_push($data, $row)
}
return $data;
}
$connectObj->closeDB();
}
Your problem is that you're overwriting the values of the previous table:
while($row = mysql_fetch_assoc($result)){
$data[0] = $row['car_id'];
$data[1] = $row['car_name'];
$data[2] = $row['car_model'];
$data[3] = $row['car_type'];
$data[4] = $row['car_price'];
}
This will just re-write the last row of data over the key's in that table.
Try:
$data = array()
while($row = mysql_fetch_assoc($result)){
array_push($data, $row)
}
Your while loop is assigning just one row to array $data. in while loop instead try this
while($row = mysql_fetch_assoc($result)){
$data["car_id"][] = $row['car_id'];
$data["car_name"][] = $row['car_name'];
$data["car_model"][] = $row['car_model'];
$data["car_type"][] = $row['car_type'];
$data["car_price"][] = $row['car_price'];
}
return $data;
Now you can iterate through the array.