SQL can't found any values - mysql

i'm having trouble returning values of sql rows, my SQL request work well on console but can't return a row of it with my code, any help ? thanks !
<?php
require_once 'sql.php';
$sqlConnexion = new mysqli($hn,$un,$pw,$db);
if($sqlConnexion->connect_error){
die ('Soucis de connexion SQL');}
$date = date("d/m/y G:i:s");
if(isset($_POST['zoneDeText'])){
$area = $_POST['zoneDeText'];
$queryone= "SELECT SortieTraitée FROM entry WHERE entréesUtilisateurs=?";
$instruction = $sqlConnexion->prepare($queryone);
if(!$instruction->prepare($queryone)){
echo "$instruction->errno";
}else{
$instruction->bind_param('s', $area);
$instruction->execute();
$result = $instruction->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)){
foreach ($row as $out){
if($out == $area){
echo $out;
}elseif($out != $area){
echo 'Still not found';
}
}
}
$instruction->close();
}
?>

You don't actually print anything, you just return the value, which makes no sense unless your code is inside a function.
if($out == $area){
return $out;
}
The documentation http://php.net/return says:
If return is called from within the main script file, then script execution ends.
Unless the code you show above has been included in another PHP script, that means it will just end the script and output nothing.
There are several other confusing things your script, but the above is probably the one directly responsible for the problem you're asking about.
Here's how I might write this code:
if (isset($_POST['zoneDeText'])) {
$area = $_POST['zoneDeText'];
$queryone = "SELECT SortieTraitée FROM entry WHERE entréesUtilisateurs=?";
$instruction = $sqlConnexion->prepare($queryone);
// if the prepare fails, it is false
if ($instruction === false) {
// false is not an object, it has no error attribute
// the error is an attribute of the connection
die($sqlConnexion->error);
}
$instruction->bind_param('s', $area);
$instruction->execute();
$result = $instruction->get_result();
// if there are zero rows in the result, the while loop
// will finish before it starts, so there will be no output
// so first check for a result of zero rows in the result
if ($result->num_rows == 0) {
echo("Found zero rows");
} else {
while ($row = $result->fetch_assoc()) {
echo $row["SortieTraitée"];
}
}
$instruction->close();
}

Related

Is it possible to use 'return' instead of 'echo' to output a wpdb query?

I have this working function meant to be used for a WordPress Multisite Database query. It's perfectly okay but I want to know if it is possible to output the desired results using return instead of echo.
Every solution and example I've come across uses echo.
function akwQueries_byMembership( $memID ){
switch_to_blog( akw_memSiteID() );
global $wpdb;
$user_id = get_current_user_id();
$prefix = $wpdb->prefix;
$membershipTable = $prefix.'membership_users_table';
$query="SELECT members_id, status
FROM $membershipTable
WHERE members_id=$memID AND user_id=$user_id AND status='active'";
$req_memid=$wpdb->get_row($query);
if( $req_memid !== null ){
// My question arises from here...
echo 'Good to go';
} else {
echo 'Not ok';
}
restore_current_blog();
}
I tried using return and it's so lifeless. I would love, for instance, to return true.
Move the restore function up above the return statement and then return the boolean.
function akwQueries_byMembership( $memID ){
switch_to_blog( akw_memSiteID() );
global $wpdb;
$user_id = get_current_user_id();
$prefix = $wpdb->prefix;
$membershipTable = $prefix.'membership_users_table';
$query="SELECT members_id, status
FROM $membershipTable
WHERE members_id=$memID AND user_id=$user_id AND status='active'";
$req_memid=$wpdb->get_row( $query );
restore_current_blog();
return $req_memid !== null;
}

Yii2 ActiveRecord add a new record with unique text field

I am using Yii2 and ActiveRecord. I have a field called "code" and for each record, it is meant to have a unique value like this: "REC0001", "REC0002", "REC0003" in a sequencial manner.
All works and I can generate a record code as described. However if I refresh my page request fast in a multiple manner (trying to test multiple requests at the same time in a very raw manner hehe), then some of the records end up with the same record code. In other words I found "REC007" a few times.
I generate the code looking at the last code and increase it by one, then I do a while foundFlag == true by checking to see if it already exists in the database.
I am suspecting there is a delay in writing to the database and hence it assumes that it is not there.
Here is a portion of the code:
static function createCode($rec){
if ($rec->code){
return $rec->code;
}
if ($rec->id){ // find it by id if one passed and record exists
$tmpRec = $rec->find()
->where([
'id' => $rec->id,
])
->one();
if ($tmpRec && $tmpRec->code){
return $tmpRec->code;
}
}
$prefix = 'REC';
if (!$prefix){
$prefix = 'REC';
}
$maxDecimals = 12;
$codeLength = $maxDecimals+strlen($prefix);
$query = $rec->find();
$query = $query->where([
'archived' => '0'
]);
// look under an organization if it exists in the model and there is one
if ($rec->hasField('organization_id') && $organization_id){
$query = addQueryWhere($query, [
'organization_id' => $organization_id,
]);
}
$query = addQueryWhere($query, [
'LENGTH(code)' => $codeLength*1,
]);
$query = $query->orderBy('code desc');
$lastRec = $query->one();
$tmpNumber = 0;
if ($lastRec && $lastRec->id){
// check what it returns
$tmpNumber = str_replace($prefix, '', $lastRec->code);
}
$tmpNumber++;
$leftDecimals = $maxDecimals - strlen($tmpNumber.'');
for ($k=0; $k <= $leftDecimals-1 ; $k++){
$tmpNumber = '0'. $tmpNumber;
}
$ret = $prefix . $tmpNumber;
return $ret;
}
public function generateCode($rec){
$foundFlag = true;
$break = 1000; // safe break point - no continuous loop
$cnt = 0;
$code = static::createCode($rec);
while ($foundFlag === true || $cnt < $break){
$tmpRec = $rec->find()
->where([
'code' => $code,
])
->one();
if (!$tmpRec->id){
$foundFlag = false;
break;
}
$time = getCurrentTimestamp();
$code = static::createCode($rec);
$cnt++;
}
$ret = $code;
return $ret;
}
So I simply call: $this->code = $this->generateCode();
Like I said it does work in generating the code, but it creates duplicates when it shouldn't!
Thank you for your assistance.

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));

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>