Adding array into mysql varchat row with comma after creating the array - php

I have a huge table with some items. I want to retrive specific items from that table according with the players level of gaming . After the code extracts all the specific items i want to add them into an array ( in this case "$cart") . I want to update a mysql row into a varchar field the array separated by a comma ",";
I tried different methods of adding them into the database but something isn't working.
Heres my code :
$sql = mysql_query("select * from iteme where tip != 'Minereu' AND tip != 'Reteta' AND tip != 'Cooking' AND tip != 'Altele' AND tip != 'Potiuni' AND tip != 'Fragment' AND tip != 'Tools' AND tip != 'Medicina' ");
$numaratoare = 0;
$cart = array();
$nivel_player = mysql_query("select * from membri where id !=0 ");
while($informatie_player = mysql_fetch_array($nivel_player))
{
$nivel_actual_player = lvl($informatie_player['experienta']);
$shop_arme_plus_5 = $nivel_actual_player + 5 ;
if ($nivel_actual_player - 5 == 0 )
$shop_arme_minus_5 = $nivel_actual_player - 5 ;
else
$shop_arme_minus_5 = 0 ;
$shop_arme = mysql_query("select * from iteme where tip = 'Arme' AND level_minim < ".$shop_arme_plus_5." AND level_minim > ".$shop_arme_minus_5." AND vandabil = 1 ");
while($informatie = mysql_fetch_array($shop_arme)) {
$numaratoare ++;
//echo " ".$informatie['nume_ro']." , ";
array_push($cart, $informatie['obiect']);
}
mysql_query("INSERT INTO membri_shop_iteme set iteme_arme = ".$informatie["obiect"]." where id_jucator = ".$informatie_player['id']." "); // Here is the problem.
}
Where's the problem? I tried adding implode(', ', $cart); but still i can't add them into database.
Thanks for helping.

may be its string problem $informatie["obiect"] to $informatie['obiect']
mysql_query("INSERT INTO membri_shop_iteme set iteme_arme = ".$informatie['obiect']." where id_jucator = ".$informatie_player['id']." "); // Here is the problem.
to
$newObject=join(",",$cart);
mysql_query("UPDATE membri_shop_iteme SET iteme_arme = '".$newObject."' where id_jucator = ".$informatie_player['id']." "); // Here is the problem.

You use $informatie["obiect"] in your query, but you have to use $cart.
while($informatie = mysql_fetch_array($shop_arme)) {
$numaratoare ++;
array_push($cart, $informatie['obiect']);
}
mysql_query("UPDATE membri_shop_iteme
SET iteme_arme = '".implode("','", $cart)."'
WHERE id_jucator = '".$informatie_player['id']."'");

Related

Prevent text from being interpreted as a number

I have a PHP/SQL app that processes invoices. Recently, I had an invoice number come in that is not being processed as text, rather as a large exponential number when I do an insert/update on associated SQL tables. For example, take an invoice number that looks like this: 123E456. PHP will try to convert this to an extremely large number due to the 'E' being bookended by numbers.
I am leaning towards this being a PHP issue because when I look at the SQL being sent to the server, it is being scripted without quotes, 123E456 rather than '123E456'.
I have tried multiple ways to try and force it to be text, but nothing seems to work.
If I put single quotes around the string, I get double single quotes in the SQL.
strval() also does not work
the issue might be in the SQL interpreter, but not entirely sure
Right now, I am instructing my clerks to put a space between the E and the numbers, which works for now. But, I am hoping to address this specific issue in the code rather than have the clerk remember to manage it on their end.
Can anyone help with how to force this as being text in the SQL clause?
OK, the code is rather my own style and is based on retrieving a dummy record (the table has 178 columns) and then populating the values into the elements that need updated. It then creates the SQL from the array and does the update. Most of this is just pre-processing to get the values needed. The database being used is Oracle.
function processF0411Z1($id, $user){
include_once $_SERVER['DOCUMENT_ROOT'].'/truck/inc/base.inc.php';
$b = '\' \'';
$z = 0;
$co = get_route_company($id);
$usrsql='SELECT `userID` from `user` where `id` = ' . $user;
$usr = openRecordset_Fetch_Assoc($usrsql);
if($usr[0]==1)$userid = $usr[1]['userID'];
else $userid = $_SESSION['username'];
$jul = date2jul(getdate());
$tjul= getJulTime(getdate());
$sql = "SELECT a.`id`, a.`carrierInvoice`, a.`carrierNbr`, a.`ivd`, a.`dgl`, b.`bol`, b.`obj_acct`, b.`allocation` FROM `route13` a inner join `route131` b on(a.`id` = b.`id`)WHERE a.`id`=".$id;
$myArr = openRecordset_Fetch_Assoc($sql);
if(isset($myArr) && $myArr[0]>0){
$carr = $myArr[1]['carrierNbr'];
$carrsql = 'select `CarrierName` from `Carriers` where `CarrierNbr` = '. $carr;
$carr_res = openRecordset_Fetch_Assoc($carrsql);
if($carr_res[0]==1)$carrName = $carr_res[1]['CarrierName'];
else $carrName = $carr;
// get the next number in the EDI Batch sequence
$nn = getJDEZFileNN();
// get the base associated array of the F0411Z1 table
$msSQL = 'SELECT * FROM PRODDTA.F59411Z1 WHERE VLEDUS=\'TRUCK\' AND VLEDBT=1';
$F0411Z1 = oracle_fetch_array($msSQL);
for($i=1;$i<=$myArr[0];$i++){
// test to see if this record exists
$tsql = "select * from PRODDTA.F0411Z1 where VLEDUS = '".strtoupper($user)."' and VLEDBT = ".$nn[1]['NNN006']." and VLEDLN = " .$i*1000;
$tres = oracle_fetch_array($tsql);
if($tres[0]>0){
$dsql = "delete from PRODDTA.F0411Z1 where VLEDUS = '".strtoupper($user)."' and VLEDBT = ".$nn[1]['NNN006']." and VLEDLN = " .$i*1000;
$count = oracle_update($dsql);
if($count === $tres[0]){
$count = $count;
}
}
$an8_sql = 'SELECT aban85 FROM PRODDTA.F0101 WHERE aban8='.$myArr[$i]['carrierNbr'];
$aban85 = oracle_fetch_array($an8_sql);
$dp = date_parse($myArr[$i]['ivd']);
$dp1 = getDate(mktime(0,0,0,$dp['month'],$dp['day'],$dp['year']));
$ivd = date2jul($dp1);//date('Y-M-d',mktime(0,0,0,$dp['month'],$dp['day'],$dp['year'])));
$dp = date_parse($myArr[$i]['dgl']);
$dp1 = getDate(mktime(0,0,0,$dp['month'],$dp['day'],$dp['year']));
$inv_no = strval($myArr[$i]['carrierInvoice']);
// index: ("VLEDUS", "VLEDBT", "VLEDTN", "VLEDLN")
$gld = date2jul($dp1);//date('Y-M-d',mktime(0,0,0,$dp['month'],$dp['day'],$dp['year'])));
$F0411Z1[1]['VLEDUS'] = '\''.strtoupper($user).'\'';//$_SESSION['userid'];
$F0411Z1[1]['VLEDLN'] = $i*1000;
$F0411Z1[1]['VLEDBT'] = $nn[1]['NNN006'];
$F0411Z1[1]['VLAN8'] = $myArr[$i]['carrierNbr'];
$F0411Z1[1]['VLPYE'] = $aban85[1]['ABAN85'];//$myArr[$i]['carrierNbr'];
$F0411Z1[1]['VLDIVJ'] = $ivd;//$myArr[$i]['ivd'];
//$F0411Z1[1]['VLDSVJ'] = $jul;
$F0411Z1[1]['VLDGJ'] = $gld;
$F0411Z1[1]['VLCO'] = $co;
$F0411Z1[1]['VLKCO'] = $co;
$F0411Z1[1]['VLAG'] = round(($myArr[$i]['allocation']*100),0);
$F0411Z1[1]['VLAAP'] = round(($myArr[$i]['allocation']*100),0);
$F0411Z1[1]['VLVINV'] = $inv_no;// <-- This element is the issue
$F0411Z1[1]['VLRMK'] = (strlen($carrName)>30?substr($carrName,0,29):$carrName);
$F0411Z1[1]['VLGLBA'] = '00573714';
$F0411Z1[1]['VLMCU'] = '1';
$F0411Z1[1]['VLTORG'] = $userid;//$_SESSION['userid'];
$F0411Z1[1]['VLUSER'] = $userid;//$_SESSION['userid'];
$F0411Z1[1]['VLPID'] = 'TRUCK';
$F0411Z1[1]['VLUPMJ'] = $jul;
$F0411Z1[1]['VLUPMT'] = $tjul;
$F0411Z1[1]['VLJOBN'] = 'TRUCK';
$F0411Z1[1]['VLURAB'] = $id;
$F0411Z1[1]['VLURRF'] = $myArr[$i]['bol'];
$z=1;
for($x=1;$x<=$F0411Z1[0];$x++){
$val1 = $F0411Z1[$x];
// first element of array is the counter, skip it
if($val1 != 1){
foreach($F0411Z1[1] as $val){
if($z==1){
$stmt = 'VALUES('.$val;
$z=99;
}
else{
if(!is_numeric($val))$val = '\''.$val.'\'';
$stmt .= ','.$val;
}
}
$stmt .= ')';
//$msSQL = 'INSERT INTO PS_PRODUCTION.PRODDTA.F0411Z1 '.$stmt;
$msSQL = 'INSERT INTO PRODDTA.F0411Z1 '.$stmt;
$count = oracle_update($msSQL);
if($count != 1) return 36;
}
}
}
}
else return 36;
return 0;
}
You can use the strval() method to cast the number as a string.
$number = 123E456;
$string = strval($number);
Or just force it to cast as a string
$string = (string) $number;

$ _GET missing in pagination

I have 2 files, the first one:
gives me the list of products
The second one:
- information relating to the product, therefore as an information page
In the first file, I implement a <a> tag, to redirect to the second file
and the variable: $id_evidenza = $row_ListaEvidenze['ID_evidenza'];
<a href="edit_evidenza.php?id=<?php echo $id_evidenza; ?>&te=<?php echo $_GET['te']; ?>" title="Modifica">
<strong><?php echo outputDecode($row_ListaEvidenze['cod_evidenza']); ?></strong>
</a
make a select query, and take my variable:
$myid_processo = "-1";
if (isset($_GET['id'])) {
$myid_processo = $_GET['id'];
}
//42320819($database_riskmanagement,$riskmanagement);
$query_processo = sprintf("SELECT * FROM tev_Evidenze WHERE tev_Evidenze.id_struttura = ".$id_str." AND tev_Evidenze.ID_evidenza = %s", GetSQLValueString($myid_processo, "int"));
$processo = mysqli_query($riskmanagement, $query_processo) or die(mysqli_error($riskmanagement));
createLog($_COOKIE['cod_operatore'], $query_processo);
$row_processo = mysqli_fetch_assoc($processo);
$totalRows_processo = mysqli_num_rows($processo);
with a do / while loop, I show the results on screen and it's ok.
Now the problems begin, because right now from the page where there are the list of products, we are in the product info page, they asked me, to implement a navigation system, which gives the possibility that if I am inside the product A, going back and forth I can scroll through the other products, without going over the product list page, and so I did by implementing this navigation system:
if($_GET['te']==""){
$sel_tipo_acc = " (ev.id_tipo_accreditamento = 0)";
}else{
$sel_tipo_acc = " (ev.id_tipo_accreditamento = ".$_GET['te'].")";
}
$my_ric_att = searchControl(trim($_GET['ric_att']));
$txt_ric = "";
$txt_ric = "Risultati per ";
$r_sql = "SELECT * FROM tev_Evidenze AS ev LEFT JOIN tev_Fatt_crit AS fc
ON fc.ID_fatt_crit = ev.id_fatt_crit
WHERE ev.id_struttura = ".$_SESSION['str']." AND ".$sel_tipo_acc." AND ";
if ($_GET['facr'] != ""){
$r_sql .= " fc.ID_fatt_crit = ".$_GET['facr']." AND ";
}
$r_sql .= " ((ev.cod_evidenza LIKE '%" .$my_ric_att. "%') OR (ev.desc_evidenza LIKE '%" .$my_ric_att. "%')) ";
$txt_ric .= trim($_GET['ric_att']) ;
$r_sql .= " ORDER BY fc.ordine_fatt_crit, ev.cod_evidenza, ev.ordine_evidenza";
$txt_ric .= "<br>";
if($_GET['v']=="all"){
$paginazione = 1;
}else{
$paginazione = 1;
}
$maxRows_ListaEvidenze = $paginazione;
$pageNum_ListaEvidenze = 0;
if (isset($_GET['pageNum_ListaEvidenze'])) {
$pageNum_ListaEvidenze = $_GET['pageNum_ListaEvidenze'];
}
$startRow_ListaEvidenze = $pageNum_ListaEvidenze * $maxRows_ListaEvidenze;
//42320819($database_riskmanagement, $riskmanagement);
$query_ListaEvidenze = $r_sql;
$query_limit_ListaEvidenze = sprintf("%s LIMIT %d, %d", $query_ListaEvidenze, $startRow_ListaEvidenze, $maxRows_ListaEvidenze);
$ListaEvidenze = mysqli_query($riskmanagement, $query_limit_ListaEvidenze) or die(mysqli_error($riskmanagement));
createLog($_COOKIE['cod_operatore'], $v_sql);
$row_processo = mysqli_fetch_assoc($ListaEvidenze);
if (isset($_GET['totalRows_ListaEvidenze'])) {
$totalRows_ListaEvidenze = $_GET['totalRows_ListaEvidenze'];
} else {
$all_ListaEvidenze = mysqli_query($riskmanagement, $query_ListaEvidenze);
$totalRows_ListaEvidenze = mysqli_num_rows($all_ListaEvidenze);
}
$totalPages_ListaEvidenze = ceil($totalRows_ListaEvidenze/$maxRows_ListaEvidenze)-1;
$queryString_ListaEvidenze = "";
if (!empty($_SERVER['QUERY_STRING'])) {
$params = explode("&", $_SERVER['QUERY_STRING']);
$newParams = array();
foreach ($params as $param) {
if (stristr($param, "pageNum_ListaEvidenze") == false &&
stristr($param, "totalRows_ListaEvidenze") == false) {
array_push($newParams, $param);
}
}
if (count($newParams) != 0) {
$queryString_ListaEvidenze = "&" . htmlentities(implode("&", $newParams));
}
}
$queryString_ListaEvidenze = sprintf("&totalRows_ListaEvidenze=%d%s", $totalRows_ListaEvidenze, $queryString_ListaEvidenze);
I have the problem in my url, I can't get all the necessary parameters in $ _GET, that is, if for example I go from product A to that B, I get this:
pageNum_ListaEvidenze=5&totalRows_ListaEvidenze=76&id=340&te=5
pageNum_ListaEvidenze=6&totalRows_ListaEvidenze=76&id=340&te=5
where the only thing that changes is the number after: pageNum_ListaEvidenze=
displaying another record, but the id is always stopped at the first record, I have this problem from this snippet of code, which I posted before:
if (isset($_GET['pageNum_ListaEvidenze'])) {
$pageNum_ListaEvidenze = $_GET['pageNum_ListaEvidenze'];
}
how do i make everything dynamic in the url?
I really understand your issue , but here is a better solution that can make the life easy .
Let's suppose that currently , you are on the info page(Page B as you describe) that show the product information .
To swip for the next product , or previous , you can try to do this :
Normaly , one the info page , you are able to get the id of the current product
$currentProductID = $_GET['id'];
Think to create a method that give you the id of the next product , the query should be like :
SELECT id FROM `product` WHERE `id` > $currentProductID limit 1
This will return the id of the next product , and then redirect to the B page with this id returned using php redirection or by clicking on the tag etc .
To do that for the previous product , just inverse the query above
with <.
Hope that help you .

Updating a row number which has been randomised

So I currently have a random number being generated in PHP and I want to know how I go about updating the row number in my selected table. Code below:
$sxiq = mysql_query("SELECT * FROM `starting_eleven` WHERE `team_id`=$uid");
$sxir = mysql_fetch_row($sxiq);
$first = rand(1,11);
$stat_changed = rand(11,31);
$up_or_down = rand(1,2);
if ($up_or_down == 1) {
$player_name = explode(" ", $sxir[$first]);
$fn = $player_name[0];
$ln = $player_name[1];
$statq = mysql_query("SELECT * FROM `players` WHERE `first_name`=$fn AND `last_name`=$ln AND `user_id`=".$_SESSION['user_id']);
$statr = mysql_fetch_row($statq);
$stat = $statr[0];
}
I would like to update the row $stat_changed from the database, but I'm not sure if this is possible without doing a long if statement, telling the code if $stat_changed = 13 $stat = pace or something along those lines, but if this is the way it must be done then I'll have to. Just thought I'd see if there was any other simpler ways of doing this.
Thanks in advance
if ($stat_changed == 13) {
//insert UPDATE statement here
}

MySQL sorting with PHP

I'm trying to accomplish the following situation:
$mysql_query = "
SELECT *
FROM st_users
WHERE
`user_comp_supervisor_id` = '$team_supervisor' AND
`user_exempt_from_goals` = '0'
ORDER BY 'calculate_progress_percent()' ASC
";
I know that I can't accomplish ordering by a function in a MySQL statement, but I'm trying to figure out how to take all the returned records, and then order them in order of highest to lowest from a php function result. Any ideas would be greatly appreciated; I've been trying to wrap my head around this for a few hours now... :-(
function diy_calc_progress_percent($user_id,$period_id,$period_week_number)
{
$this->user_id = $user_id;
$this->period_id = $period_id;
$this->period_week_number = $period_week_number;
if ($this->period_week_number == 1)
{
$this->week_id = mysql_result( mysql_query(" SELECT `period_week_one` FROM `st_comp_periods` WHERE `period_id` = '$this->period_id' "),0 );
}
else if ($this->period_week_number == 2)
{
$this->week_id = mysql_result( mysql_query(" SELECT `period_week_two` FROM `st_comp_periods` WHERE `period_id` = '$this->period_id' "),0 );
}
else
{
echo "Week number not valid.";
exit();
}
$this->week_start_date = mysql_result( mysql_query(" SELECT `week_start_date` FROM `st_comp_weeks` WHERE `week_id` = '$this->week_id' "),0 );
$this->week_end_date = mysql_result( mysql_query(" SELECT `week_end_date` FROM `st_comp_weeks` WHERE `week_id` = '$this->week_id' "),0 );
$this->user_department = $this->user_info($this->user_id,"user_comp_department_id");
$this->user_week_diy_goal = mysql_result( mysql_query(" SELECT `goal_diy_department` FROM `st_comp_department_goals` WHERE `goal_department_id` = '$this->user_department' AND `goal_week_id` = '$this->week_id' "),0 );
$this->calc_totals_result = mysql_query("SELECT SUM(record_total_diy_revenue) AS user_week_total FROM `st_entered_records` WHERE `record_user_id` = '$this->user_id' AND `record_date` BETWEEN '$this->week_start_date' AND '$this->week_end_date'");
$this->calc_totals_row = mysql_fetch_assoc($this->calc_totals_result);
$this->user_week_total = $this->calc_totals_row['user_week_total'];
$this->user_week_one_percent = ($this->user_week_total / $this->user_week_diy_goal) * 100;
$this->user_week_one_percent = number_format( (float)$this->user_week_one_percent, 2, '.', '' );
return $this->user_week_one_percent;
}
You probably will have to do some array juggling.
First get all your entries FROM st_users into a first array (mysql_query)
Then you could run through that array, and for each entry you do the calculate_progress_percent() and build up a second array in which you could add the additional info ("user_progress_percent").
After this you can sort the new array ba your new info ("user_progress_percent").
And here is some quick and dirty code-suggestions – code is however not tested… of course…:)
First:
$mysql_query = "SELECT * FROM st_users
WHERE `user_comp_supervisor_id`='$team_supervisor' AND
`user_exempt_from_goals` = '0'";
Then something like this:
$i = 0;
while($tmp = mysql_fetch_array($mysql_query)) {
$my_second_array[$i]['user_id'] = $tmp['user_id'];
$user_id = $my_second_array[$i]['user_id'];
diy_calc_progress_percent($user_id,$period_id,$period_week_number);
$my_second_array[$i]['user_result'] = $diy_calc_progress_percent_result;
$i++;
}
And then sorting that second array should be possible as described here:
Sort Multi-dimensional Array by Value
…hope this helps at some point…

Displaying tagged images across multiple pages fails

I feel this is a more logic problem than anything. A database has pictures saved via a source reference and booleans for tags e.g. isLandscape=1. I had made a system to traverse pages of results based on types asked. The following is an example of what I'm facing. I only see the same 12 pictures from page 0 -> page 22. Then I start to see new ones. I think I have just been overlooking this bug since I had not noticed it until now. One thing I noticed was page22*12pictures = 264 which is the same as the first new picture id that is seen. You can see the error here (just change the p to different pages).
<?php
$pictureid = -1;
$startpage = 0;
$viewsection = -1;
$uid = -1; //user id
$amntperrow = 4; //how many pictures per row, must correlate with doThumb()'s switch case amounts
$maxrows = 3; //how many rows of pictures to drop
if(isset($_GET['pid']) && is_int(intval($_GET['pid']))) $pictureid = clean($_GET['pid']);
if(isset($_GET['sec']) && is_int(intval($_GET['sec']))) $viewsection = clean($_GET['sec']);
if(isset($_GET['p']) && is_int(intval($_GET['p']))) $startpage = clean($_GET['p']);
$result = generateResult(array("isFlowers"), $startpage);
//**snip** -- drawing thumbnails would happen here
function generateResult($types, $page) {
global $amntperrow;
global $maxrows;
$sqlWheres = "";
$idAmnt = ($amntperrow*$maxrows)*$page;
if(isset($types) && !empty($types)) {
if(count($types) >= 1) {
for($i = 0; $i<count($types); $i++) {
$sqlWheres .= $types[$i] . "='1'";
if($i < count($types)-1) $sqlWheres .= " AND ";
}
}
}
$result = "SELECT * FROM pictures WHERE ";
if(!empty($sqlWheres)) $result .= $sqlWheres . " AND " ;
$result .= " private='0' AND id >='" . $idAmnt . "' LIMIT " . ($amntperrow*$maxrows);
return $result;
}
?>
This seems like a glaring bug that I am overlooking. Thanks for the help.
What is the difference between these two queries?
SELECT *
FROM pictures
WHERE private = '0' AND id >= '24'
LIMIT 12;
and
SELECT *
FROM pictures
WHERE private = '0' AND id >= '36'
LIMIT 12;
Answer: potentially no difference at all. The database engine can decide in either case that it wants to return pictures with ids 100 through 111 - that result set meets all of the conditions of either query.
Try a query like this instead:
"SELECT *
FROM pictures
WHERE private = '0'
ORDER BY id
LIMIT " . $idAmnt . ", " . ($amntperrow * $maxrows)
The ORDER BY id is really the key. Paging through database results is generally done with a combination of ORDER BY and LIMIT.

Categories