简体   繁体   中英

Filter out unset mysqli_query

I am trying to dynamically set some sql's based on variable values..

So I if i have

$somevariable = "somevalue" I set some $sql and $a1 = mysqli_query($con, $sql1)
$somevariable2 = "somevalue2" I set some $sql2 and $a2 = mysqli_query($con, $sql2)

and so on..

Now I want to run these queries and if any of them is FALSE i want to rollback

So here is what I have done..

mysqli_autocommit($con, FALSE);
if ($a1 and $a2 and $a3 and $a4 and $a5 and $a6)
{
mysqli_commit($con);
}
else
{
mysqli_rollback($con);
}

Now my problem is $a can be any number and also any number in between also might not be there like $a1 and $a7 only or something like that.

So if I say ($a1 and $a2 and $a3 and $a4 and $a5 and $a6) it does not do commit because one of the variables is not there.

If i give ($a1 or $a2 or $a3 or $a4 or $a5 or $a6) it runs only the first query and does commit.

So how can I give as many variables as I have set and filter out the unset variables before I give 'and' for commit

I have tried

$tmp = array($a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8,$a9,$a10); 
$filtered = array_filter($tmp); 
$one = implode("and", $filtered)
if ($one)
{
mysqli_commit($con);
}
else
{
mysqli_rollback($con);
}

but it wont work either.. any idea? Thanks.

You don't need to use explicit variables for each interaction unless you want them for later. You can use [] to append the result to the array so that you aren't leaving unassigned members, and use array_reduce to evaluate.

function bool_and($a,$b) { return $a and $b; }
$result_array = array();
$result_array[] = mysqli_query($con, $sql1)
$result_array[] = mysqli_query($con, $sql2)
$result_array[] = mysqli_query($con, $sql7)

if (array_reduce($result_array,"bool_and",true))
{
    mysqli_commit($con);
}
else
{
    mysqli_rollback($con);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM