How to fetch row from custom table in drupal 7? - mysql

I have used
$member_id = 12;
$results = db_query("select * from {customorders} where id = :fid", array(':fid' => $member_id));
foreach($results as $result) {
$name = $result['name'];
}
but I get error Fatal error: Cannot use object of type stdClass as array
so what could be solution , and please correct me if I have written wrong query for select
i want "select * from customorders where id = 12"
and customorders is my created custom table in Drupal database
Please help me..
Thanks

The $result variable is returned as an array of objects. So you should use $result->name instead of $result['name'].
Your code can be fixed to be like that:
$member_id = 12;
$results = db_query("select * from {customorders} where id = :fid", array(':fid' => $member_id));
foreach($results as $result) {
$name = $result->name; // THE EDITED LINE.
}
Hope this works... Muhammad.

This worked for me:
$member_id = 12;
$results = db_query("select * from {customorders} where id = :fid", array(':fid' => $member_id))->fetchAll();
foreach($results as $result) {
$name = $result->name; // THE EDITED LINE.
}
Note the fetchAll() which resulted in the actual data, without this I got the database object only.

Related

Entering an array to the firstOrCreate generates an error Laravel 5.7

I am running the firstOrCreate on my controller with the following code:
private function validateNumberBD($areaCodes,$numbers){
$arrayAreaCodes = array();
foreach ($areaCodes as $key => $value) {
$arrayAreaCodes[] = $value->AREACODES_ID;
}
$consultArray = array();
for($i = 0; $i < count($numbers); $i++){
for($j = 0; $j < count($arrayAreaCodes);$j++){
$consultArray[] = (['PHONE' => $numbers[$i],'AREACODES_ID' => $arrayAreaCodes[$j]]);
}
}
//dd($consultArray);
$searchOrCreate = Phone::firstOrCreate($consultArray);
}
My problem is generated since executing that code generates the following error:
If I do a dd () to my $ consultArray variable, it shows me the following array
If I change the position of the array values, I get this error:
Consulting the new array would look like this.
I think my mistake is in how to list the data, but I really don't know what else to do.
In query mode, how do I know how many values ​​the firstOrCreate creates for me?
firstOrCreate cannot check or insert multiple records and you are sending an array of arrays.
for($i = 0; $i < count($numbers); $i++){
for($j = 0; $j < count($arrayAreaCodes);$j++){
$searchOrCreate = Phone::::firstOrCreate(
['PHONE' => $numbers[$i], 'AREACODES_ID' => $arrayAreaCodes[$j]]);
}
}
This could work.

Get data into array using mysql prepared statements

I'm trying to get the function below to return an array of user_ids. Here is the function in php.
function users_following($follower_id)
{
include "dbconn.php";
$stmt = mysqli_prepare($con, "SELECT user_id FROM follo WHERE follower_id = ?");
mysqli_stmt_bind_param($stmt, "i", $follower_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $following_user_id);
$count = 0;
$user_array = array();
while (mysqli_stmt_fetch($stmt) ) {
$user_array[] = $following_user_id;
$count = $count + 1;
}
mysqli_stmt_close($stmt);
if ($count > 0)
{
return $user_array;
} else {
return false;
}
}
The problem is that the above function just returns the output: 'Array' (without quotes), when I tested with the code below, not the list of user_ids.
$userid_array = users_following($_SESSION["user_id"]);
echo $userid_array;
Can anyone please help me out? If you need additional details, just comment below and I will try to clarify.

Creating Json file from mysql

i can't get more than one return in this json. when the original query returns 90k results.
i can't figure out what's hapening.
also the return i get isn't organized as it should. it return the following
{"material":["R8190300000","0"],"grid":["R8190300000","0"]}
sorry to ask this i have been looking for an answer but couln't get it in the internet.
<?php
$link = mysqli_connect("localhost","blablabla","blablabla","blablabla");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query =" SELECT material,grid FROM ZATPN";
if( $result = mysqli_query( $link, $query)){
while ($row = mysqli_fetch_row($result)) {
$resultado['material']=$row;
$resultado['grid']=$row;
}
} else {
echo"doesnt work";
}
file_put_contents("data.json", json_encode($resultado));
?>
The problem is that you are overriding the value for the array keys:
$resultado['material']=$row;
$resultado['grid']=$row;
At the end you will have only the last 2 rows; I suggest you to use something like:
$resultado['material'][] = $row;
$resultado['grid'][] = $row;
This will save you pair rows in $resultado['grid'] and unpaired rows in $resultado['material'];
After the information in comments you can use this code:
$allResults = array();
while ($object = mysqli_fetch_object($result)) {
$resultado['id'] = $object->id;
$resultado['name'] = $object->name;
$resultado['item'] = $object->item;
$resultado['price'] = $object->price;
$allResults[] = $resultado;
}
file_put_contents("data.json", json_encode($allResults));

mysql_fetch_assoc in MeekroDB

Excuse me for being new to MeekroDB library, I wonder how to check for rows in the login process;
$query = DB::query("SELECT * FROM users WHERE username=%s",$username);
$numrows = DB::count($query);
// this needs the edit
if ($numrows!=0){
while($row = mysql_fetch_assoc($query)){
$dbusername = $row['username'];
$dbpassword = $row['password'];}
You need to bear in mind that your variable $query is now an array (if any records are found) so you do not need to do
while($row = mysql_fetch_assoc($query))
Instead try
foreach ($query as $user)
{
$dbusername = $user['username'];
$dbpassword = $user['password'];
}
Also, if you have more then one record with the same username and password then you may be doing something wrong with your user registration/maintenance process.

Was: Grab the last inserted id - mysql Now: Where should we call the last insert id?

Here's the thing, I don't have access to code that inserts data into a given table. However, I need to add related additional data into another table. So, I was thinking about grabbing the last inserted ID and from there... insert the related data into that other table.
Since I don't have access to the statement, I believe that mysql last insert id function will be of no use here.
All the PDO::lastInsertId examples that I see, are also attached to some "insert query" before it, so no use as well.
How can I grab the last inserted ID on the cases were we DON'T have access to the original insert statement ?
Data flow:
It starts here: signup.tpl
Where we have:
onclick="checkoutvalidate();return false"
On the js we have:
function checkoutvalidate() {
$.post("order/index.php", 'a=validatecheckout&'+$("#orderfrm").serialize(),
function(data){
if (data) {
...
} else {
document.orderfrm.submit();
}
});
So, now, let's look for "validatecheckout" into index.php
And we found it:
We can't read along this lines, anything concerning the insertion. The immediately after that I can get is, after the conditional statement - right ?
if ($a=="validatecheckout") {
$errormessage = '';
$productinfo = getProductInfo($pid);
if ($productinfo['type']=='server') {
if (!$hostname) $errormessage .= "<li>".$_LANG['ordererrorservernohostname'];
else {
$result = select_query("tblhosting","COUNT(*)",array("domain"=>$hostname.'.'.$domain,"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Cancelled"),"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Terminated"),"domainstatus"=>array("sqltype"=>"NEQ","value"=>"Fraud")));
$data = mysql_fetch_array($result);
$existingcount = $data[0];
if ($existingcount) $errormessage .= "<li>".$_LANG['ordererrorserverhostnameinuse'];
}
if ((!$ns1prefix)OR(!$ns2prefix)) $errormessage .= "<li>".$_LANG['ordererrorservernonameservers'];
if (!$rootpw) $errormessage .= "<li>".$_LANG['ordererrorservernorootpw'];
}
if (is_array($configoption)) {
foreach ($configoption AS $opid=>$opid2) {
$result = select_query("tblproductconfigoptions","",array("id"=>$opid));
$data = mysql_fetch_array($result);
$optionname = $data["optionname"];
$optiontype = $data["optiontype"];
$qtyminimum = $data["qtyminimum"];
$qtymaximum = $data["qtymaximum"];
if ($optiontype==4) {
$opid2 = (int)$opid2;
if ($opid2<0) $opid2=0;
if ((($qtyminimum)OR($qtymaximum))AND(($opid2<$qtyminimum)OR($opid2>$qtymaximum))) {
$errormessage .= "<li>".sprintf($_LANG['configoptionqtyminmax'],$optionname,$qtyminimum,$qtymaximum);
$opid2=0;
}
}
}
}
$errormessage .= checkCustomFields($customfield);
if (!$_SESSION['uid']) {
if ($_REQUEST['signuptype']=="new") {
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$companyname = $_REQUEST['companyname'];
$email = $_REQUEST['email'];
$address1 = $_REQUEST['address1'];
$address2 = $_REQUEST['address2'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$postcode = $_REQUEST['postcode'];
$country = $_REQUEST['country'];
$phonenumber = $_REQUEST['phonenumber'];
$password1 = $_REQUEST['password1'];
$password2 = $_REQUEST['password2'];
$temperrormsg = $errormessage;
$errormessage = $temperrormsg.checkDetailsareValid($firstname,$lastname,$email,$address1,$city,$state,$postcode,$phonenumber,$password1,$password2);
$errormessage .= checkPasswordStrength($password1);
} else {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (!validateClientLogin($username,$password)) $errormessage .= "<li>".$_LANG['loginincorrect'];
}
}
if (($CONFIG['EnableTOSAccept'])AND(!$_REQUEST['accepttos'])) $errormessage .= "<li>".$_LANG['ordererrortermsofservice'];
$_SESSION['cart']['paymentmethod'] = $_REQUEST['paymentmethod'];
if ($errormessage) echo $_LANG['ordererrorsoccurred']."<br /><ul>".$errormessage."</ul>";
else {
if ($_REQUEST['signuptype']=="new") {
$userid = addClient($firstname,$lastname,$companyname,$email,$address1,$address2,$city,$state,$postcode,$country,$phonenumber,$password1);
}
}
//DO THE DO INSERT_LAST_ID() here ?
}
Thanks in advance,
MEM
After the insert statement you can fire another query:
SELECT LAST_INSERT_ID();
and this will return one row with one column containing the id.
Docs: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
mysql> SELECT LAST_INSERT_ID();
-> 195
This works per connection so there is no problem if another thread writes into the table. But your SELECT needs to be executed 'RIGHT AFTER'/'As the next query' after the insert query ran
Edit
An example:
$dbConnection = MyMagic::getMeTheDatabase("please");
$oSomeFunkyCode->createThatOneRowInTheDatabase($dbConnection);
$result = $dbConnection->query("SELECT LAST_INSERT_ID();");
// ... fetch that one value and you are good to go
If the column is a simple auto_incrementing integer, you could use SELECT MAX(MyAutoincrementingColumn) FROM MyTable. You might risk selecting a row that has been inserted by another user in the meantime, if your users are not using transactions.
If you don't have access to the last INSERT line, you can make a subquery to find the last inserted id:
select max(id) from <table>