I'm not really much into PHP or mySQL so I hope you can help me.
I got a php script with a function that returns a json with all the entries in a database table:
public function select($table, $wheres = null)
{
$connect = $this->connect();
if ($wheres == null)
{
$query = mysqli_query($connect, 'SELECT * FROM `'.$table.'`');
} else {
$query = mysqli_query($connect, 'SELECT * FROM `'.$table.'` WHERE '.$this->wheres($wheres));
}
$i = 0;
$ret = array();
while ($row = mysqli_fetch_assoc($query)) {
foreach ($row as $key => $value) {
$ret[$i][$key] = $value;
}
$i++;
}
return ($ret);
}
Edit:
I have my application which calls this function. Everything worked as expected but then I added 2 more fields to one of the tables ( 1 text, 1 varchar ), and now when I call this function it returns nothing ; literally an empty string.
I've also noticed that if I just delete those new fields it works, which is kinda annoying plus I need those fields and I can't figure out where the problem root is.
Also, the application code is not the problem: when this function is called it only passes 2 parameters (the method name, and the table name), it can't be wrong.
By the way, here is the table structure if it may help you help me:
pic related
This function helps you to get data form database in json from , this return json
<?php
function getData($tbl_name=null,$id=null)
{
$con = mysqli_connect("localhost","root","","mydb"); //my db is my database name
if(!$con){ die( "could't connect with database" ); }
$sql = mysqli_query($con,'SELECT * FROM $tbl_name WHERE id = {"$id"}');
while($row = mysqli_fetch_assoc($sql))
{
#echo"<pre>";
#print_r($row); //this will return data form data base in array from
return json_encode($row);
}
}
?>
Related
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"];
So do not have an idea why this function is not working? i am trying to select all the ids from the table but nothing is selected.
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows = ('value'=>$record, 'label'=>$record);
}
return $rows;
}
this function below works fine, I need the function above to do the same as teh function below.
public function toOptionArray()
{
return array(
array('value'=>1, 'label'=>'one'),
array('value'=>2, 'label'=>'Two'),
array('value'=>3, 'label'=>'Three'),
array('value'=>4, 'label'=>'Four')
);
}
There are a couple of issues with your code:
You're only selecting a single item (id, but later, I assume you're expecting an ID and a value).
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
record is an array from your SQL query, so you should be treating it as such. eg. $record['id']
$rows you want as an array, but you're overwriting it each time, so $rows[] = makes more sense
Something like:
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id, label FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows[] = array('value'=>$record['id'], 'label'=>$record['label']);
}
return $rows;
}
Try using the core read/write resource. Change
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
To
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
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");
I've been trying to get a series of nested loops working to select the database name from one table then query the selected table in that database, and add up the results and display the number of them and the database name.
I have gotten the code to work but it keeps displaying:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I have tried every way possible I have found online to help, but none work.
$resulta = mysql_query("SELECT dbname AF012 FROM Customer");
while($data = mysql_fetch_array($resulta))
{
$db = $data[' dbname '];
$result = null;
$result2 = mysql_query("SELECT changemade FROM $db.orders");
//looping through the results
while($row = mysql_fetch_array($result2))
{
//checking if any record is 1,2 or 3
if( ($row[‘changemade’]== 1) || ($row[‘changemade’]== 2) || ($row[‘changemade’]== 3) ) {
//if any match the if adding 1 to the counter
$counter ++;
}
}
unset($result2);
echo $db." ".$counter;
echo "<br>";
$counter = 0;
$result = null;
$result2 = null;
}
All the database connections are made and work fine, so it has nothing to do with that. Any help would be great.
You need to introduce error handling, also you can streamline your code. The current point of failure is querying the database and fetching from it, so you can encapsulate it into a function of it's own which will also reduce your code:
function mysql_query_array($query)
{
if (!$result = mysql_query($query)) {
throw new Exception(sprintf('Invalid query "%s", error: %s.', $query, mysql_error()));
}
return function () use ($result) {
return mysql_fetch_array($result);
};
}
With that little helper function, your code is now more compact and it has actual error handling:
$queryA = mysql_query_array("SELECT dbname AF012 FROM Customer");
while ($data = $queryA())
{
$counter = 0;
$queryB = mysql_query_array("SELECT changemade FROM {$data['dbname']}.orders");
while ($row = $queryB())
{
if (in_array($row['changemade'], range(1, 3))) {
$counter++;
}
}
printf("%s %s<br>\n", $db, $counter);
}
This is caused by the fact that mysql_query return false if the query fails, so one of your query fails and mysql_fetch_array() gets a boolean. Try changing $db = $data[' dbname ']; to $db = $data['dbname'];
I have succeeded in querying one table to get information that is needed to query another table (If you can see a better way I would be grateful!)
My question is: How can I have multiple values come back from the first query and have my second query come back with multiple results.
As you can see I am inserting the returned result from query one into query two “msg_id = ?”(I use '$datas' to fill the ‘?’) but if my results from query one have multiple values then how will this work?
Also how can I make it get multiple results from query one? at the moment if there are multiple values in mysql it only grabs the first one it reads.
My MODEL code is as follows:
function check() {
$this->db->select('msgto_message');
$this->db->from('msgto');
$this->db->where('msgto_display', 'y');
$this->db->where('msgto_recipient', '1');
$w = $this->db->get();
if ($w->num_rows() > 0) {
$rowe = $w->row_array();
$datas = $rowe['msgto_message'];
}
$sql = "SELECT msg_content FROM msg WHERE msg_id = ?";
$data = $this->db->query($sql, $datas) or die(mysql_error());
if ($data->num_rows() > 0) {
foreach($data->result_array() as $row) {
$data = $row;
}
return $data;
}
}
My CONTROLLER code is as follows:
function index() {
$this->load->model('data_model');
$data['rows'] = $this->data_model->check();
$this->load->view('home', $data);
}
Thank you anyone that helps me, I greatly appreciate it!
You may find a database join helpful here. While I'm not entirely sure what you're trying to do here (especially in that foreach loop!), something like this might get you going in a more efficient direction:
function check() {
$this->db->select('msg.msg_content');
$this->db->from('msgto');
$this->db->join('msg', 'msgto.msgto_message = msg.msg_id');
$this->db->where('msgto.msgto_display', 'y');
$this->db->where('msgto.msgto_recipient', '1');
$data = $this->db->get();
if ($data->num_rows() > 0) {
return $data->result_array();
}
}
This asks the database to join together the msg and msgto tables based on msgto_message matching msg_id, and can use the WHERE critera on msgto while returning the results from msg.
Right not you are getting only the first row from query one
if ($w->num_rows() > 0) {
$rowe = $w->row_array();
$datas = $rowe['msgto_message'];
}
To get all the records you need to cycle through the result
if ($w->num_rows() > 0) {
foreach($rowe = $w->row_array() as $datas) {
$datas = $rowe['msgto_message'];
$sql = "SELECT msg_content FROM msg WHERE msg_id = ?";
$data = $this->db->query($sql, $datas) or die(mysql_error());
if ($data->num_rows() > 0) {
foreach($data->result_array() as $row) {
$data = $row;
}
return $data;
}
}
}