having trouble looping sql insert with php - php

I'm new to php and sql and what im trying to achieve is loop an sql insert into the same column with different values form another table with different columns i am able to do it without loop but i cant seem to get it to work with this loop. any help would be greatly appreciated.
edited.
i want to insert the sum values of table tblplyrbetlisttemp to tblcollplasada depending if $vresults == 'SK-WALA' or $vresults == 'SK-MERON' the outcome should insert 3 rows with fldM7 fldW7 and fldM7price or fldW7price depending on $vresults value.
table structure listed below
+-----------------------------------------+
| tblplyrbetlisttemp |
+-----------------------------------------+
| fldM7price | fldW7price | fldM7 | fldW7 |
+------------+------------+-------+-------+
+--------------------------------------------------------------------------------------------------------+
| tblcollplasada |
+--------------------------------------------------------------------------------------------------------+
| fldtag | fldtranno | fldfightno | fldtrandate | fldusrcd | fldwinner | fldpercomm | fldSK | fldarenaid |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
for example $vresults is equals to 'SK-WALA' and table tblplyrbetlisttemp has values fldM7=5 fldW7=5 fldW7price=500
+-----------------------------------------+
| tblplyrbetlisttemp |
+-----------------------------------------+
| fldM7price | fldW7price | fldM7 | fldW7 |
+------------+------------+-------+-------+
| 500 | | 5 | |
+------------+------------+-------+-------+
| | 500 | | 5 |
+------------+------------+-------+-------+
output should be
+--------------------------------------------------------------------------------------------------------+
| tblcollplasada |
+--------------------------------------------------------------------------------------------------------+
| fldtag | fldtranno | fldfightno | fldtrandate | fldusrcd | fldwinner | fldpercomm | fldSK | fldarenaid |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
| | | | | | SK-WALA | | 500 | |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
| | | | | | SK-WALA | | 5 | |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
| | | | | | SK-WALA | | 5 | |
+--------+-----------+------------+-------------+----------+-----------+------------+-------+------------+
code:
function CollectComm ($vresults) {
global $iSqlConnDb;global $varfightno;global $percomm;global $comm ;global $vtagid;global $ActvARenId;
if ($vresults == 'SK-WALA') { $win = 'W';$lose = 'M'; }
if ($vresults == 'SK-MERON') { $win = 'M';$lose = 'W'; }
$winOdd =array('fld' . $win . '7price','fld' . $win . '7','fld' . $lose .'7');
$query_rscoll = "select distinct(fldusrcd) as vuser from tblplyrbetlisttemp where fldarenaid='$ActvARenId'";
$rscoll = mysql_query($query_rscoll, $iSqlConnDb) or die(mysql_error());
$row_rscoll = mysql_fetch_assoc($rscoll);
$totalRows_rscoll = mysql_num_rows($rscoll);
if ($totalRows_rscoll > 0) {
do {
$vhave = false;
$varuserid = $row_rscoll['vuser'];
$vtrandate = date("Y-m-d G:i:s");
for ($i = 0; $i < count($winOdd); $i++) {
$OC[$i] ='';
$varodd = $winOdd[$i];
$rsTotcomm = mysql_query("select SUM($varodd) as totodd FROM tblplyrbetlisttemp where fldarenaid='$ActvARenId' and fldusrcd='$varuserid'");
$vcomm=mysql_fetch_assoc($rsTotcomm);
if ($vcomm['totodd'] > 0 || ) {
$vhave = true;
$OC[$i] =$comm * $vcomm['totodd'] ;
}
if ($vhave == true) {
$vtranno = AutoIDArena('tblcollplasada','fldtranno',$ActvARenId);
$insertSQL = "INSERT INTO tblcollplasada(fldtag,fldtranno,fldfightno,fldtrandate,fldusrcd,fldwinner,fldpercomm,fldSK,fldarenaid)
VALUES(" . $vtagid . "," . $vtranno . "," .$varfightno . ",'" . $vtrandate . "','" . $varuserid . "','" . $vresults . "','" . $percomm . "','" . $OC[$i] . "','" . $ActvARenId . "')";
$Result1 = mysql_query($insertSQL, $iSqlConnDb) or die(mysql_error());
}
}
}
while ($row_rscoll = mysql_fetch_assoc($rscoll)); }
}

Related

Generate JSON booleans from Db

I need to generate a JSON String using this format:
{"content":{"brands":1},"brands":[{"id":"1","name":"brand 1","description":"description","icon":"icon","url":"example.com","categories":{"1":"true","2":"true","3":"false","4":"false","5":"false","6":"false"}},{"id":"2","name":"brand2","description":"description","icon":"icon","url":"example.com","categories":{"1":"true","2":"true","3":"false","4":"false","5":"false","6":"false"}}]}
From this tables:
brands:
| id | name | description | icon | url |
|----|--------|-------------|------|-----|
| 1 | name 1 | description | icon | url |
| 2 | name 2 | description | icon | url |
| 3 | name 3 | description | icon | url |
| 4 | name 4 | description | icon | url |
| 5 | name 5 | description | icon | url |
| 6 | name 6 | description | icon | url |
categories:
| id | name | description | icon | url |
|----|--------|-------------|------|-----|
| 1 | name 1 | description | icon | url |
| 2 | name 2 | description | icon | url |
| 3 | name 3 | description | icon | url |
| 4 | name 4 | description | icon | url |
| 5 | name 5 | description | icon | url |
| 6 | name 6 | description | icon | url |
objects:
| id | id_brand | id_category |name | description | icon | url |
|----|----------|-------------|-------|-------------|------|-----|
| 1 | 1 | 1 |name 1 | description | icon | url |
| 2 | 1 | 2 |name 2 | description | icon | url |
| 3 | 2 | 1 |name 3 | description | icon | url |
| 4 | 2 | 2 |name 4 | description | icon | url |
this is my relevant code so far
public function actionBrand($id = null) {
if (empty($id)) {
// Obtiene datos de la base
$sql = "SELECT DISTINCT objects.id_brand AS id, brands.name AS name, brands.description AS description, brands.icon AS icon, brands.url AS url, objects.id_category, categories.name AS category " .
"FROM objects " .
"LEFT JOIN brands ON objects.id_brand = brands.id " .
"LEFT JOIN categories ON objects.id_category = categories.id " .
"ORDER BY objects.id_brand, objects.id_category ";
} else {
// Obtiene datos de la base
$sql = "SELECT DISTINCT objects.id_brand AS id, brands.name AS name, brands.description AS description, brands.icon AS icon, brands.url AS url, objects.id_category, categories.name AS category " .
"FROM objects " .
"LEFT JOIN brands ON objects.id_brand = brands.id " .
"LEFT JOIN categories ON objects.id_category = categories.id " .
"WHERE brands.id = " . (int) $id . " " .
"ORDER BY objects.id_brand, objects.id_category ";
}
$data = Yii::$app->db->createCommand($sql)
->queryAll();
// Obtiene categorias
$categories = Yii::$app->db->createCommand('SELECT id FROM categories ORDER BY id')
->queryAll();
if (!empty($data)) {
// Construye primer registro
$brands[0]['id'] = $data[0]['id'];
$brands[0]['name'] = $data[0]['name'];
$brands[0]['description'] = $data[0]['description'];
$brands[0]['icon'] = $data[0]['icon'];
$brands[0]['url'] = $data[0]['url'];
$total = count($data);
for ($i = 1, $j = 0; $i < $total; $i++) {
if ($brands[$j]['id'] == $data[$i]['id']) {
continue;
} else {
$j++;
$brands[$j]['id'] = $data[$i]['id'];
$brands[$j]['name'] = $data[$i]['name'];
$brands[$j]['description'] = $data[$i]['description'];
$brands[$j]['icon'] = $data[$i]['icon'];
$brands[$j]['url'] = $data[$i]['url'];
}
}
} else {
$brands = array();
}
// Construye y envia JSON
$json['content']['brands'] = count($brands);
$json['brands'] = $brands;
echo json_encode($json);
}
It generates the first part of the JSON that i need, but im stuck at the categories part i need to select the data from the base and convert it to id : (true)(false) on each brand
{"content":{"brands":1},"brands":[{"id":"1","name":"brand 1","description":"description","icon":"icon","url":"example.com"},{"id":"2","name":"brand2","description":"description","icon":"icon","url":"example.com"}]}
Can you help me?
Regards
After you are done building the brands, loop on the categories, searching brands for the existing id match. If it matches, then adjust a true false value for the categories. Then when the categories are completed, append them to every brand in a final loop.
$cleancats = [];
foreach ($categories as $cat) {
$result = false;
foreach($brands as $brand) {
if ($cat['id'] == $brand['id']) {
$result = true; break;
}
}
$cleancats[ $cat['id'] ] = $result;
}
array_walk ($brands,function(&$brand) use ($cleancats) {
$brand['categories'] = $cleancats;
});
(note put this after your for ($i = 1, $j = 0; $i < $total; $i++) loop ends)
That should get the categories to every brand in brands, as you would like.
If you need the categories to be a LITERAL "true" and "false" then adjust this one line above:
$cleancats[ $cat['id'] ] = ($result?'true':'false');

How declare the data in column mysql

Can someone help me, I wanna declare the data from column "status".
If 'green' then the value is 1.
If 'yellow' the value is 2.
If 'red' the value is 3.
And then all of that value can make line graph using PHP language.
name: 'Data Status',
data: [
<?php
$sql = "SELECT * FROM monitoring";
$result = mysqli_query($koneksi, $sql);
while ($data = mysqli_fetch_array($result))
{
?>
<?php echo $data["status"]?>, <?php
}?>
]
But I know the data cannot load properly because the type data is string.
+---------+------------+----------+----------+
| id_data | time | status | date |
+---------+------------+----------+----------+
| 1 | 05.00 | green | 01-01-18 |
| 2 | 05.30 | green | 02-01-18 |
| 3 | 05.30 | red | 03-01-18 |
| 4 | 05.30 | green | 04-01-18 |
| 5 | 05.15 | yellow | 05-01-18 |
| 6 | 05.20 | yellow | 06-01-18 |
| 7 | 05.11 | red | 07-01-18 |
| 8 | 05.05 | red | 08-01-18 |
| 9 | 05.22 | green | 09-01-18 |
+---------+------------+----------+----------+
<?php
$sql = "SELECT * FROM monitoring";
$result = mysqli_query($koneksi, $sql);
while ($data = mysqli_fetch_array($result)) {
switch ($data["status"]){
case 'green':
$value = 1;
break
case 'yellow':
$value = 2;
break;
case 'red':
$value = 3;
break;
default:
$value = 0;
break;
}
echo $data["status"] . ' ' . $value;
}
Possible the easiest would be a case statement in the sql
SELECT
`id_data`,
`time`,
`date`,
case
when `status`='green' then 1
when `status`='yellow' then 2
when `status`='red' then 3
end as `status`
FROM `monitoring`

How does the mysqli execute function work internally?

I have a DB where I have some tables, most of them irrelevant for this question:
Content_handler:
+-------------+-------------------+---------------------------+
| app_data_id | app_menu_entry_id | content_item_container_id |
+-------------+-------------------+---------------------------+
| 0 | 0 | NULL |
| 0 | 1 | bm9zb3Ryb3MtMC0w |
+-------------+-------------------+---------------------------+
App_menu_entry:
+-------------------+----------+---------+--------------+
| app_menu_entry_id | position | name | icon_id |
+-------------------+----------+---------+--------------+
| 0 | 0 | Nombre | asd |
| 1 | 1 | Precios | icontest.png |
+-------------------+----------+---------+--------------+
Content_item_container:
+---------------------------+--------------+
| content_item_container_id | content_name |
+---------------------------+--------------+
| bm9zb3Ryb3MtMC0w | Nosotros |
+---------------------------+--------------+
content_handler.app_menu_entry_id REFERENCES TO app_menu_entry.app_menu_entry_id
content_handler.content_item_container_id REFERENCES TO content_item_container.content_item_container_id
Now, when I want to update app_menu_entry I DELETE all records from this table (with cascade, so also deletes content from content_handler) and then I insert data with PHP from an array so I use a foreach with prepared statements like this:
$menuQuery = $connection->prepare("INSERT INTO app_menu_entry(app_menu_entry_id,position,name,icon_id) VALUES(?,?,?,?)");
$handlerQuery = $connection->prepare("INSERT INTO content_handler(app_data_id, app_menu_entry_id, content_item_container_id) VALUES(?,?,?)");
$id = 0;
if (!$menuQuery || !$handlerQuery) {
ErrorHandler::setError(ErrorHandler::DB_QUERY_ERROR, true);
throw new \Exception('Error al realizar la consulta');
}
foreach ($menu['menu_items'] as $menuItem) {
$name = $menuItem['name'];
$position = $menuItem['position'];
$icon = $menuItem['icon_id'];
$contentId = ($menuItem['content'] != null) ? base64_encode($menuItem['content'] . '-' . $userId . '-' . $appId) : null;
$menuQuery->bind_param('ssss', $id, $position, $name, $icon);
$menuQuery->execute();
$handlerQuery->bind_param('sss', $appId, $id, $contentId);
$handlerQuery->execute();
$id++;
}
The problem is that this loop insert data in app_menu_entry but not in content_handler. This can be solved adding sleep(1000); between execute() function and that make me think how can I prevent using sleep() and how this execute function works? Does it uses a thread, makes a async queue...?

getting an empty array when my pdo should be returning many mysql rows

I get array(0){} where I should be returning rows;
<?php
require_once('auth.php');
$conn = new PDO("mysql:host=localhost;dbname=$dbname", $username, $pw);
$file = fopen('nameList1.txt','r');
$firstname = ''; $lastname = ''; $index = -1; $id = -1;
$tab = ' ';
try{
while ($line = fgets($file)) {
$index = strrpos($line, $tab);
$firstname = substr($line, 0, $index);
//var_dump($firstname);
$lastname = substr($line, $index + strlen($tab));
//var_dump($lastname);
$stmt = $conn->prepare("SELECT * FROM dbname WHERE FName = :firstname AND LName = :lastname");
$stmt->bindvalue(':firstname', $firstname);
$stmt->bindvalue(':lastname', $lastname);
$stmt->execute();
$result = $stmt->fetchAll();
var_dump($result);
}
}
catch ( Exception $e )
{
echo "Exception at $i";
}
fclose($file);
?>
********* working SQL *************
mysql> SELECT * FROM list WHERE FName='TARA' AND LName='AABA';
+----+--------------+---------------+-------+-------+-------+-----------+------------+-----------+--------+----------+-----------+-----------+-----------+-------------+-------------------+--------------------+------------+------------+----------+------------+------------+--------------+--------------+---------------------+-----------------------+-------+-------+-------+-------+----------+---------+-------------+------------------+--------------+------------+------------+
| id | StateVoterID | CountyVoterID | Title | FName | MName | LName | NameSuffix | Birthdate | Gender | RegStNum | RegStFrac | RegStName | RegStType | RegUnitType | RegStPreDirection | RegStPostDirection | RegUnitNum | RegCity | RegState | RegZipCode | CountyCode | PrecinctCode | PrecinctPart | LegislativeDistrict | CongressionalDistrict | Mail1 | Mail2 | Mail3 | Mail4 | MailCity | MailZip | MailCountry | Registrationdate | AbsenteeType | LastVoted | StatusCode |
+----+--------------+---------------+-------+-------+-------+-----------+------------+-----------+--------+----------+-----------+-----------+-----------+-------------+-------------------+--------------------+------------+------------+----------+------------+------------+--------------+--------------+---------------------+-----------------------+-------+-------+-------+-------+----------+---------+-------------+------------------+--------------+------------+------------+
| 9 | 0 | 458198 | | TARA | L | AABRA | | 2 | F | 5804 | | 1ST | PL | | | NE | 0 | MARYSVILLE | WA | 98271 | 0 | 101231 | 0 | 39 | 2 | | | | | | | | 05/05/2004 | P | 11/08/2011 | A |
*********** var_dump($result) **************
array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } ....
Empty array returned by fetchAll means there was no data found.
This is a fact. While "working SQL" is working somewhere else.
So - you have to check your input data, database, environment, typos and such.
Sincerely,

Coordinates from MySQL to HTML table (PHP, PDO, MySQL)

I am creating game which uses MySQL database to create "playing field".
In my MySQL table I have two columns pointX and pointY, both INT. I could also use POINT, but in my case these two columns are better solution.
| id | pointX | pointY | player | game |
|----|--------|--------|--------|------|
| 1 | -2 | 1 | 7 | 10 |
| 2 | -3 | 2 | 5 | 10 |
| 3 | 2 | -2 | 2 | 10 |
| 4 | -2 | -1 | 1 | 10 |
I should produce HTML table from this MySQL table. Something like this, but with no coordinateheaders (below those are only for easier understanding):
|-----|----|----|----|----|----|----|
| Y/X | -3 | -2 | -1 | 0 | 1 | 2 |
|-----|----|----|----|----|----|----|
| -2 | | | | | | 2 |
|-----|----|----|----|----|----|----|
| -1 | | 1 | | | | |
|-----|----|----|----|----|----|----|
| 0 | | | | | | |
|-----|----|----|----|----|----|----|
| 1 | | 7 | | | | |
|-----|----|----|----|----|----|----|
| 2 | 5 | | | | | |
|-----|----|----|----|----|----|----|
Plus.. every <td> should have attribute data-cell, which includes coordinates, as example data-cell="-2x-1".
What is the best way to get started?
$rng = $dbh->prepare('
SELECT MIN(pointX) AS minX, MIN(pointY) AS minY,
MAX(pointX) AS maxX, MAX(pointY) AS maxY
FROM field
WHERE game = ?
LOCK IN SHARE MODE
');
$qry = $dbh->prepare('
SELECT pointX, pointY, player
FROM field
WHERE game = ?
ORDER BY pointX, pointY
');
$dbh->beginTransaction();
$rng->execute([$game_id]);
$qry->execute([$game_id]);
$dbh->rollBack();
$limits = $rng->fetch();
$player = $qry->fetch();
echo '<table>';
for ($y = $limits['minY']; $y <= $limits['maxY']; $y++) {
echo '<tr>';
for ($x = $limits['minX']; $x <= $limits['maxX']; $x++) {
printf('<td data-cell="%dx%+dy">', $x, $y);
if ($player and $player['pointX'] == $x and $player['pointY'] == $y) {
echo htmlentities($player['player']);
$player = $qry->fetch();
} else {
echo ' ';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
It looks like you are already off to a good start. Assuming the number of cells for X and Y as $xcells and $ycells, the next step I would take is to build your table like so:
echo "<table>";
for ($i = -3; $i < $ycells; i++) {
echo "<tr>";
for ($j = -3; $j < $xcells; j++) {
echo "<td data-cell='" . $i . "y" . $j . "x'>";
}
echo "</tr>";
}
echo "</table>";

Categories