I'm experiencing a strange issue while running a mysql query from php.
I have a mysql database with many (23) tables; two of them are Users and FollowersList.
FollowersList contains two colums: in the first one there's the code of a user, and in the second one the code of the user that the first one is following; each column references the primary index of Users table.
I have defined a stored procedure called "getFollowings" that returns the codes of the users that someone is following; it is defined in this way:
CREATE PROCEDURE getFollowings(IN cod INT(11))
BEGIN
SELECT Code2 FROM FollowersList WHERE Code1=cod;
END
When I call the stored procedure from phpmyadmin, everything works fine; I get all the correct results.
When I call it from php, using this code:
$sql0="CALL getFollowings('".$cod."')";
$res0=mysqli_query($con, $sql0);
$array0=mysqli_fetch_array($res0);
mysqli_next_result($con);
I can't get the correct results. The connection is defined correctly, and all the variables are correctly defined.
Let's make an example. I'm working on the user with code 94; when I run the procedure from phpmyadmin, I get two results: 63 and 89, which is correct in my database.
If I try the same from a php script, I get an array of dimension 2, but with only the first value; the var_dump is:
array(2) { [0]=> string(2) "63" ["Code2"]=> string(2) "63" }
This means that I receive and array with size=2, but with only one element stored. Do you have any idea why?
You are not iterating the mysqli_fetch_array.
Use like this
while($row = mysqli_fetch_array($res0)){
$array0[] = $row;
}
print_r($array0);
and you are using mysqli_fetch_array which give both associative array and numeric array.
If you want associative array use
mysqli_fetch_array($res0,MYSQLI_ASSOC);
If you want numeric array use
mysqli_fetch_array($res0,MYSQLI_NUM);
as default it return both
use like this
while($row = mysqli_fetch_array($res0)){
$array0[] = $row;
}
echo count($array0);
foreach($array0 as $value){
echo $value[0];
}
Related
I am trying to access a SINGLE VALUE from a row but the dd(); is getting the whole row and showing it in the Collection array. The code:
$last_id = \App\Cat::limit(1)->orderBy('cat_id','desc')->get(['cat_id']);
dd($last_id);
So when I need the JUST "55" value I get :
"cat_id" => "55"
Same happens with others columns, when I need JUST the "Eletronics" I get:
"cat_name" => "Eletronics"
I have already tried lots of stuff like Limit, List, First and nothing happens, when I try to call something like dd($lastId->cat_id ); it gives me a "Undefined property" error. SO now I am really out of options since I am using the documentation example and even that way it does not works fine. So any help would be great, thank you.
I think you don't understand that the Model represents entire row of table.
That means that $last_id in your code:
$last_id = \App\Cat::limit(1)->orderBy('cat_id','desc')->get(['cat_id']);
represents entire row of cats table. If you want to get id, you have to do this:
$cat = \App\Cat::first(1)->orderBy('cat_id','desc')->get();
dd($cat->id);
What more, if you write
$cat = \App\Cat::first();
you will get first cat from cats table, and then you can access every column of this row as property of $cat object
If Laravel says you that property cat_id is undefined, propably your table don't contain cat_id column.
Already got it, i change the get for the "value" method.
\App\Cat::orderBy("id","desc")->value("id");
I have an external database that I am trying to access from within a Drupal page, I have successfully queried the database and output data to the page using fetchAssoc(), however this only returns the first row in the database. I would like to return all rows into an array for processing, so I'm attempting to use fetchAllAssoc(), this however results in an exception. The database has the following SQL fields:
id, model, manufacturer, url, date_modified
My test code is as follows:
<?php
db_set_active('product_db');
$query = db_select('product', 'p')->fields('p');
$sqlresults = $query->execute()->fetchAllAssoc('id');
foreach($sqlresults as $sqlresult)
{
printf($sqlresult);
}
db_set_active();
?>
I'm thinking that it is the key field 'id' that I am specifying with fetchAllAssoc() that is the problem, as fetchAssoc() prints values correctly. All documentation I have found seems to say that you pass a database field as the key but I have also passed a numeric value with no success.
Many thanks in advance for any advice, I'm sure I'm just missing something stupid.
I think it should work in this way, but within the foreach you want to print the $sqlresult variable as a string, but it is an object (it causes the error).
printf function needs a string as the first parameter, see:
http://php.net/manual/en/function.printf.php
Use for instance var_dump instead:
var_dump($sqlresult);
Is there any way to print the resource_id without mysql_fetch_array.I dont want to loop through result.I want print only the first row at top.I know mysql has been depreciated.This is for old project.
You can make use of arrays in your case
$all_rows = array();
.
. // your query
.
while($dbrow = mysql_fetch_array($query))
{
$all_rows[] = $dbrow;
}
$first_row_array = $all_rows[0]; // first row will be stored here
/*
uncomment the below line if you do not want to use the
first row again while looping through the remaining
rows
*/
/* unset($all_rows[0]); */
foreach($first_row_array as $first_row)
{
// do something with first row data
}
foreach($all_rows as $dbrow)
{
// loop through all the rows returned including the first row
}
A resource in itself is a pretty meaningless type. It only means something to specific functions, like mysql_*. When querying the database, there are certain resources allocated on the MySQL server which hold your requested result; PHP doesn't really have access to those results yet. To give you a handle on those resources on the MySQL server, you get a resource type variable. It's basically just your ticket, saying "if you ever want to access that data waiting for you on the MySQL server, use this number."
So, if you want to output the data from the MySQL server, you will have to fetch it from there, e.g. with mysql_fetch_assoc. That then returns the data to you which you can print.
If you just want the first result, just call that function once.
I need assistance on how to return results from database queries using the MySQL SUM() function with Laravel. I know I need to use raw database queries and I've tried that but it seems to only return me an array.
This is the code I have so far:
$cron_jobs = DB::select('
SELECT ROUND(SUM((TIME_TO_SEC(TIMEDIFF(end_time, start_time))/60)/15))
AS cron_jobs
FROM `quiet_periods`');
var_dump($cron_jobs);
exit;
And this is my console log:
array(1) {
[0]=>
object(stdClass)#689 (1) {
[cron_jobs]=>
string(2) "20"
}
}
The objective for me is to pull the value 20 from the returned result yet I can't seem to achieve this. When I run the following code:
echo $cron_jobs;
It should only show the value of the key / value pair.
Please note: I have also used DB::statement yet that returns the result of 1 which I am assuming is a Boolean result. I don't get why though... Oh, and I have used DB::raw within the DB::select but that only seems to return the same result.
Use standard accessors to get to your data
$crons = $cron_jobs[0]->cron_jobs;
I don't know what Laravel version we are talking, but in 4 you got:
DB::selectOne($sql);
Ok basically I can't figure out how to get the imploded result from mysql back to a usable variable in php. The array is throwing me for a loop, and driving me nuts.
The checkboxes that are being dynamically created from the db:
<input name="tournament_id[]" value="'.$row['tournament_id'].'" type="checkbox">'.$row['tournament_name'].'
The posted value getting imploded (no sql injection prevention implemented yet):
$got_tournament_id = implode(",",$_POST['tournament_id']);
This gets inserted into mysql like this:
id user_id tournament_id
1 16942627 1,10
This is my mysql query to grab the imploded data:
$query = ("SELECT tournament_id FROM tournament WHERE user_id=16942627");
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$got_it = $row['tournament_id'];
}
$bust_him = var_dump(explode(",", $got_it));
echo $bust_him;
The above using var_dump is returning the following:
array(2) { [0]=> string(1) "1" [1]=> string(2) "10" }
Now this is where I am totally lost, and can't figure out what to do to get the values 1 and 10 from the array into individual variables. I have tried several ways to do it and I keep ending up with errors, or just the word array. I need some help if anybody can give some. Thanks in advance.
Don't var_dump(), whose purpose is debugging, not code or display logic. Just store the output of explode() into $bust_him (what a weird variable name):
// Store the output of explode() directly
$bust_him = explode(",", $got_it);
// No need for individual variables, just access via array keys.
echo $bust_him[0];
echo $bust_him[1];
// etc...
If you have a fixed number of elements, you can use list() to place into variables:
// You know you only have two, so you can use list()
// to store directly into variables
list($first, $second) = explode(",", $got_it);
echo $first;
echo $second;
In the long run, a better solution than storing comma-separated values in your table is to create a separate, properly normalized table which links tournament_id to user_id. You then have multiple rows per user_id, each containing one tournament_id. This makes for much simpler and more efficient querying in a lot of instances, enabling the use of COUNT() aggregates for example, among many other benefits.