PHP code execution sequence - php

I am trying to execute some lines of php code, but it seems that tey are not being execute in the required order. Here is a code snippet:-
if( !empty($_POST['val']) )
{
$val = Get_Val($sid, $_POST['val'], $lnk);
if($val)
{
echo "<br />Here Value : " . $val;
}
else
{
echo "Invalid Value.";
}
}
When I echo the value before returning in function Get_Val() it shows a positive number for some set of valid arguments, which means that the If-condition is true, but when I execute the code the Else part is being executed. Though the output appear in order, they are not consistent. I hope I have made the problem clear.
Any amount of help is appreciated. Thanks!
Here is Get_Val() function:-
function Get_Val( $sid, $a, $link)
{
//check is name is already present in table
$query = "SELECT val FROM store WHERE name = \"" . $a . "\""; //val is auto incremented in sql
$result = mysql_query( $query ,$link ) or die( mysql_error());
if($result)
{
$count = mysql_num_rows($result);
if( $count == 0 ) //insert name and the return val
{
$query_x = "INSERT INTO store(name) VALUES('" . $a . "')";
$result = mysql_query( $query_x ,$link ) or die( mysql_error());
if($result)//If new name inserted then return the 'val'
{
Get_Val($sid, $a,$link);
}
}
else
{
$row = mysql_fetch_assoc( $result );
echo "Val in Get_Val : " . $row['val'];
return $row['val'];
}
}
else
{
echo "Unexpected Error Occured...!!!";
exit(0);
}
}

what's with this:
if( $count Val in Get_Val : " . $row['val'];
return $row['val'];
}
are you sure that $_POST['val'] is a valid value that is stored in the db?

Get_Val does not return a value if $count == 0. Add a return statement before the recursive call. Like this:
...
if( $count == 0 ) //insert name and the return val
{
$query_x = "INSERT INTO store(name) VALUES('" . $a . "')";
$result = mysql_query( $query_x ,$link ) or die( mysql_error());
if($result)//If new name inserted then return the 'val'
{
return Get_Val($sid, $a,$link);
}
}
...

Related

How to use single for each loop for multiple array to update single sql statement

I want to use single for each for two array.
array 1 : has path of images (path is dynamic as per user need)
array 2: has values description field of each image (description is dynamic as per user need)
I want to insert both array in sql table using only one sql statement.
<?php $sql="INSERT INTO posts(title,description,category,createdBy,pictureURL,CreatedAt) VALUE ('$title',
'$description','$category','$creatdby','Admin/PostImages/$finalpath',now());";
$result = mysqli_query($conn,$sql);
if($result)
{
$upload_directory = 'PostImages/';
$field_values_array = $_REQUEST['desc'];
$x=0;
foreach($field_values_array as $value1){
foreach ( $_FILES['photo']['name'] AS $key => $value ){
//Move file to server directory
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory . $_FILES["photo"]["name"][$x])){
$finalpath=$upload_directory . $_FILES["photo"]["name"][$x];
}
if (isset($_SESSION['p_id'])){
$p_id = $_SESSION["p_id"];
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) VALUES ('$p_id','$value1','$finalpath')";
$result1 = mysqli_query($conn,$sql1);
$x++;
}
}
header("Location: uploadpost_test.php");
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
} ?>
I refactor and clean up your codes. Try this.
if(isset($_SESSION['p_id']))
{
$p_id = $_SESSION["p_id"];
}
$values = '';
$next = ',';
$len = count($field_values_array);
foreach($field_values_array as $x=>$value1)
{
if(move_uploaded_file($_FILES["photo"]["tmp_name"][$x], $upload_directory.$_FILES["photo"]["tmp_name"][$x]))
{
$tmp_name = $_FILES["photo"]["tmp_name"][$x];
$finalpath = $upload_directory.$tmp_name;
$next = $x >= $len-1 ? '' : $next;
$values .= "VALUES('$p_id','$value1','$finalpath')".$next;
}
}
$sql1="INSERT INTO `postimages`(`p_id`,`description`, `img_path`) $values";
$result1 = mysqli_query($conn,$sql1);

PHP Mysqli insert into database with large iterations

Below I have Php code that loops through an array and for each it checks if the value already exists in the database and if not, create it. The code itself is working but the loop itself can be insanely big, maximum of a couple tens thousand iterations.
How can I optimize this code? What to use and how to use. There should be a better way to insert this many times without looping through each individual.
foreach($arr as $value){
$checkID = mysqli_query($cenn, "SELECT item_id from items WHERE item_id = '$value'");
if (!$checkID) {
die("Query '$checkID' failed to execute for some reason");
}else{
if (mysqli_num_rows($checkID) > 0) {
$user = mysqli_fetch_array($checkID);
echo "item_id" . checkID . "exists already";
}
else{
echo "item_id: '$user_id' doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $user_id); //12452 30704
$gw2Api_result = json_decode($gw2Api,true);
/*Here would be some code to determine values that are being inserted*/
if (!array_key_exists("description",$gw2Api_result)) {
$description = 'No description available...';
} else{
if($gw2Api_result['description'] === ''){
$description = "No description available...";
} else {
$description = $gw2Api_result['description'];
}
}
$insertItem = "INSERT INTO items
(item_id, name, description,
AccountBindOnUse, AccountBound,
last_update
)
VALUES ('$user_id', '$gw2Api_result[name]', '$description',
'$AccountBindOnUse', '$AccountBound', CURRENT_TIMESTAMP)";
if ($cenn->query($insertItem) === true) {
echo "New record '$user_id' created successfully";
} else {
echo "Error: " . $sql . "<br>" . $cenn->error;
}
}
}
} // end foreach
The question: How to insert many values, new rows, into mysqli database as fast as possible.
Just use bulk insert.
Collect all the rows for insertion and pass it in one query.
echo 'hi';
if (!empty($arr)) {
echo 'ok';
$values = "'" . implode("', '", $arr) . "'";
$qExistingItemIds = mysqli_query($cenn, "SELECT item_id from items WHERE item_id IN($values)");
$existingItemIds = [];
while ($existingItemId = mysqli_fetch_array($qExistingItemIds)) {
$existingItemIds[] = $existingItemId['item_id'];
}
$arr = array_diff($arr, $existingItemIds);
$inserts = array();
$i = 0;
$ic = count($arr);
foreach ($arr as $value) {
$i++;
echo "item_id: $value doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $value); //12452 30704
$gw2Api_result = json_decode($gw2Api,true);
/*Here would be some code to determine values that are being inserted*/
if (!array_key_exists("description", $gw2Api_result)) {
$description = 'No description available...';
} else {
if ($gw2Api_result['description'] === '') {
$description = "No description available...";
} else {
$description = $gw2Api_result['description'];
}
}
$inserts[] = "
('$value', '$gw2Api_result[name]', '$description', '$AccountBindOnUse', '$AccountBound', CURRENT_TIMESTAMP)
";
if ($i == 50 OR $i == $ic) {
$inserts = implode(",", $inserts);
$insert = "
INSERT INTO items
(item_id, name, description, AccountBindOnUse, AccountBound, last_update)
VALUES
$inserts
";
if ($cenn->query($insert) === true) {
echo 'great';
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $cenn->error;
}
$ic -= 50;
$i = 0;
$inserts = array();
}
}
}
so now we have only 2 queries. not thousands
details about bulk insert:
http://www.geeksengine.com/database/data-manipulation/bulk-insert.php
If you use prepared statement you should reduce the round trips to the database server and only compile and optimise each query once instead of Number_of_inputs * 2 queries. This should reduce the workload.
I would be very interested to know by how much.
$sql = "SELECT item_id from items WHERE item_id = ?";
$db_select = $cenn->prepare($sql);
if ( ! $db_select ) {
echo $cenn->error;
exit;
}
$sql_insert = "INSERT INTO items
(item_id, name, description,
AccountBindOnUse, AccountBound, last_update)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)";
$db_insert = $cenn->prepare($sql);
if ( ! $db_insert ) {
echo $cenn->error;
exit;
}
foreach($arr as $value){
$db_select->bind_param('i', $value);
$res = $db_select->execute()
if ( $res === FALSE ) {
echo $cenn->error;
exit;
}
if ($db_select->num_rows > 0) {
// dont bother fetching data we already know all we need to
$user = $db_select->free();
echo "item_id $value exists already";
} else {
echo "item_id: $value doesn't exist<br>";
$gw2Api = file_get_contents("https://api.guildwars2.com/v2/items/" . $value);
$gw2Api_result = json_decode($gw2Api,true);
if ( ! array_key_exists("description",$gw2Api_result)
|| $gw2Api_result['description'] === '') {
$description = 'No description available...';
} else{
$description = $gw2Api_result['description'];
}
$db_insert->bind_param('issss', $value, $gw2Api_result[name],
$description, $AccountBindOnUse,
$AccountBound)
if ($cenn->query($insertItem) === true) {
echo "New record $value' created successfully";
} else {
echo "Error: " . $sql_insert . "<br>" . $cenn->error;
}
}
} // end foreach

php mysql return wrong boolean result

I have the following query :
'SELECT Active FROM tbUsers WHERE Id=55'
The Id is unique and I need just to know the status of the user if he's active yes or no. The Column Active is set as boolean in Mysql
When I tried to return the result like the following (using another php function) :
$result = $this->selectRow($db,"tbClass","Active","Id='$Id'");
if($result) { return "ok" ; } else { return "nok" ;)
it returns 'ok' on both cases.
Any idea what's wrong with it ?
Here is the other function :
public function selectRow($db,$tableName,$field,$where) {
if($where == "") {
$query = "SELECT $field FROM $tableName";
}
else
{ $query = "SELECT $field FROM $tableName WHERE $where"; }
$result=$db->Qry($query);
if ($result) {
$no_of_rows = $db->TotRows($result);
if($no_of_rows == 1) {
return $result;
}
if($no_of_rows == 0) {
return '';
}
if($no_of_rows < 0) {
die('Invalid query: ' . $sender ."(".$query ."): ".mysql_errno().": ". mysql_error());
return '';
}
}
else {
die('Invalid query: ' . $sender .": " .$query.": ". mysql_errno().": ". mysql_error());
return '';
}
}
Qry Function is the following :
function Qry($sql) {
if($result = mysqli_query($this->con,$sql) ) {
return $result;
}
else
{
$err = "Error: ".$sql. " :: ". mysqli_error;
die("$err");
}
}
I think you need to change this condition .
$result=$db->Qry($query);
always return you query object
Just remove this condition and
You need to count number of affected row
<?php
public function selectRow($db, $tableName, $field, $where) {
if ($where == "") {
$query = "SELECT $field FROM $tableName";
} else {
$query = "SELECT $field FROM $tableName WHERE $where";
}
$result = $db->Qry($query);
$no_of_rows = $db->TotRows($result);
if ($no_of_rows == 1) {
return $result;
}
if ($no_of_rows == 0) {
return FALSE;
}
if ($no_of_rows < 0) {
die('Invalid query: ' . $sender . "(" . $query . "): " . mysql_errno() . ": " . mysql_error());
return FALSE;
}
}
Alright, so $result is a mysqli_result object.
You might want to fetch the first row of that result and return the desired column.
Replace
return $result;
with
return $result->fetch_assoc()[$field];

first column data is missing in while loop when mysql_fetch_array()

i have a problem with while loop.In this first column data is not getting remaining data is getting here is my code
$result_By_Vendor_And_Title = mysql_query("select * from cek6q_jshopping_products where vendor_id = " . $vendor . " and name_en-GB='" . $title . "'");
if (mysql_fetch_array($result_By_Vendor_And_Title)) {
echo 'found';
while ( $rows = mysql_fetch_array($result_By_Vendor_And_Title) ) {
echo $id = $rows['product_id'];
}
}
echo 'not found';
Here i want to display all the ids but i have getting all the ids except first one how i can get first one.
Because the fetch_array you do to test for found is fetching and discarding the first row
just try this
$result_By_Vendor_And_Title = mysql_query("select * from cek6q_jshopping_products where vendor_id = '" . $vendor . "' and name_en-GB='" . $title . "'");
if($result_By_Vendor_And_Title){
if(mysql_num_rows($result_By_Vendor_And_Title)>0){
echo 'found';
while ( $rows = mysql_fetch_array($result_By_Vendor_And_Title) ) {
echo $id = $rows['product_id'];
}
}else{
echo 'not found';
}
}
Try:
if( mysql_num_rows( $result_By_Vendor_And_Title ) > 0 ) {
echo 'found';
while ( $rows = mysql_fetch_array($result_By_Vendor_And_Title) )
{ echo $id = $rows['product_id']; }
}else{
echo 'not found';
}
Dont use mysql_* functions.

PHP - bind_result to array

I'm using a prepared statement for a query that returns multiple results, which I'd want to have in an array. But bind_result won't work with arrays, so this is how I do it:
$read_items = $db->stmt_init();
$read_items->prepare("SELECT item_id, item_name FROM items");
$read_items->execute();
$read_items->bind_result($var1, $var2);
while ($read_items->fetch()) {
$item_id[] = $var1;
$item_name[] = $var2;
}
Is there clearer/better/more elegant way to put results into $item_id and $item_name arrays?
As it's visible from above, I'm using $var1 and $var2 like "intermediates" - and constantly have feeling there must be a better way.
Thanks.
I can't take credit for it, but the PHP manual has a nice solution (pasted verbatim):
<?php
// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);
// returns a copy of a value
$copy = create_function('$a', 'return $a;');
$results = array();
while ($mysqli_stmt_object->fetch()) {
// array_map will preserve keys when done here and this way
$results[] = array_map($copy, $byref_array_for_fields);
}
You can use the Argument unpacking(...) operator.
$results = array(null, null);
$read_items->bind_result(...$results);
while ($read_items->fetch()) {
$item_id[] = $result[0];
$item_name[] = $result[1];
}
I really don't see the point of putting your item id's and item names in different arrays, you're breaking up a single object in two collections for ??? no reason . yes.
So, going back to this, what you should be doing is :
$items[$i]['var1']=$var1;
$items[$i]['var2']=$var2;
But this of course is still not very good.
The correct solution is to have a function that maps your mysqli result to an array so you can directly start working on that, whatever the query, here's mine - works in a few db's but not all are up to date at the moment :
function connectmysqldb($database,$host,$port,$user,$password){
global $conn;
$conn=mysqli_connect($host, $user, $password, $database,$port);
if (!$conn){
die('Error: Could not connect: ' . mysqli_connect_error());
}
return $conn;
}
function connectpgdb($database,$host,$port,$user,$password){
$connectString = 'host=' . $host . ' port=' . $port . ' dbname=' . $database . ' user=' . $user . ' password=' . $password;
$conn = pg_connect ($connectString);
if (!$conn)
{
die('Error: Could not connect: ' . pg_last_error());
}
return $conn;
}
function connectmssqldb($dbname,$host,$port,$uid,$pw){
$connectionOptions = array("UID"=>$uid,"PWD"=>$pw);
$conn = sqlsrv_connect( $host, $connectionOptions);
if (!$conn)
{
die('Error: Could not connect: ' . print_r( sqlsrv_errors(), true));
}
return $conn;
}
function sqlec($query,$dbtype,$dbname,$host,$port,$uid,$pw){
switch($dbtype){
default:
$res="Database Type not Recognized : $dbtype";
break;
case "mysql":
global $conn;
if(!isset($conn)){
$conn=connectmysqldb($dbname,$host,$port,$uid,$pw);
}
$clone=mysqli_multi_query($conn,$query);
if(!$clone){
die('Error: ' . mysqli_error($conn));
}else{
$clonearray=array();
$i=0;
if ($clone = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_assoc($clone)){
$clonearray[$i]=$row;
$i++;
}
mysqli_free_result($clone);
}
$res=$clonearray;
}
break;
case "postgres":
$conn=connectpgdb($dbname,$host,$port,$uid,$pw);
$clone=pg_query($conn,$query);
if (!$clone)
{
die('Error: ' . pg_last_error());
}else{
$clonearray=array();
$i=0;
while ($row = pg_fetch_row($clone))
{
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
$clonearray[$i][pg_field_name($clone,$y)] = $c_row;
next($row);
$y = $y + 1;
}
$i = $i + 1;
}
pg_free_result($clone);
pg_close($conn);
$res=$clonearray;
}
break;
case "mssql":
$conn=connectmssqldb($dbname,$host,$port,$uid,$pw);
$res=sqlsrv_query($conn,$query);
if (!$res)
{
die( "Error in statement execution.\n".print_r( sqlsrv_errors(), true));
}else{
$i=0;
$sqlsarray=array();
while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC))
{
if($i==0){
$arrk=array_keys($row);
}
$j=0;
while($j<count($arrk)){
$sqlsarray[$i][$arrk[$j]]=$row[$arrk[$j]];
$j++;
}
$i++;
}
$res=$sqlsarray;
}
break;
}
return $res;
}
function local_sqlec($query){
global $db_server;
global $db_db;
global $db_port;
global $db_username;
global $db_password;
return sqlec($query,"mysql",$db_db,$db_server,$db_port,$db_username,$db_password);
}
Which I use like this :
$r=local_sqlec("SELECT test1,test2 FROM test");
$i=0;
echo "last id =".($r[0]['test1'])."<br>";
echo "Row count =".($r[0]['test2'])."<br>";
while($i<$r[0]['test2']){
echo "inserted id =".($r[0]['test1']+$i)."<br>";
$i++;
}

Categories