I'm trying to make an ad system with PHP pdo. How can I get result id's of the following SQL query into my PHP variables?
SELECT id FROM ads, ( SELECT id AS sid FROM ads WHERE position="A" ORDER BY RAND( ) LIMIT 5 ) tmp WHERE ads.id = tmp.sid
I just don't know how to get those values in the variables like this:
$ad_1 = result[1]
$ad_2 = result[2]
$ad_3 = result[3]
$ad_4 = result[4]
$ad_5 = result[5]
With the help of those variables ($ad_1...5) I could display unique and random ads in different places, get correct data, and update ad clicks/views...
Best to get into the habit of using prepared statements like this:
<?php
$adIds = array();
$position = 'A'; // probably set dynamicaly
$stmt = $dbh->prepare("SELECT id FROM ads, ( SELECT id AS sid FROM ads WHERE position=? ORDER BY RAND( ) LIMIT 5 ) tmp WHERE ads.id = tmp.sid");
$stmt->bindParam(1, $position);
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
$adIds[] = $row[0];
}
}
?>
$adIds is now an array containing all the ids returned from the select statement.
try this :
$begin = "ad_";
for($i = 0; $i < 6 ; $i++) {
$($begin.$i) = $result[$i];
}
(assuming you array $result is previously defined)
Related
I am currently building a leaderboard (https://mgo.io/mgo3/leaderboard.php) and I'm having issues making it manually accept data. I want it to grab data from my MySQL database, and allow me to manually go in and enter data which it will in turn display as well. It currently grabs id, and clan names from the clans db.
How do I get it to read data I input from two new 'wins' and 'losses' columns I add in the db it already grabs data from?
Heres my code:
<?php
include_once "Log.class.php";
include_once "dbcon.php";
function getLeaders() {
global $dbh;
date_default_timezone_set('UTC');
$res = array();
$stmt = $dbh->prepare("SELECT id, name FROM clans ORDER BY id ASC");
$stmt->execute();
while ($row = $stmt->fetch()) {
$clan_id = (int) $row['id'];
$clan_name = $row['name'];
$res[$clan_id] = array();
$res[$clan_id]['name'] = $clan_name;
$res[$clan_id]['rank'] = 0;
$res[$clan_id]['cp'] = 0;
$res[$clan_id]['win'] = 0;
$res[$clan_id]['loss'] = 0;
?>
Just add the fields to your SELECT statement and assign the retrieved values to the appropriate variables:
// Add wins & losses here:
$stmt = $dbh->prepare("SELECT id, name, wins, losses
FROM clans ORDER BY id ASC");
$stmt->execute();
while ($row = $stmt->fetch()) {
$clan_id = (int) $row['id'];
$clan_name = $row['name'];
$res[$clan_id] = array();
$res[$clan_id]['name'] = $clan_name;
$res[$clan_id]['rank'] = 0;
$res[$clan_id]['cp'] = 0;
$res[$clan_id]['win'] = $row['wins']; // <<<< and here...
$res[$clan_id]['loss'] = $row['losses']; // <<<<
I am setting a cookie everytime a user views an image, and then when they view another I modify that cookie to also have a value including the last image id viewed.
E.g.
First image: Cookie = 0;
For each after: Cookie = 0,3,4,6,1,44,2
etc.
I am then checking for that cookie, getting the value and trying to put into a query:
$value = 0;
// check for cookie
if ( isset($_COOKIE['viewed']) ) {
$value = $_COOKIE['viewed'];
}
$stmt = $conn->prepare("SELECT * FROM images where id NOT IN (:viewed) ORDER BY rand() LIMIT 1");
$stmt->execute([':viewed' => $value]);
But this isn't taking any affect on the result returned.
If I hardcode the NOT IN to (1,2,4) then it will eliminate those results.
In my JSON return I check what the string is:
$return['cookie'] = $value;
And the value shows:
"cookie":"0,3,3,2,2,2,2,3,2,2,1,1,1,1,2,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,1,3,2,2,3,3,2,2,3,2,2,2,1"
How can I get this to work?
Try this:
$value = 0;
// check for cookie
if ( isset($_COOKIE['viewed']) ) {
$value = $_COOKIE['viewed'];
}
$stmt = $conn->prepare("SELECT * FROM images where id NOT IN (:viewed) ORDER BY rand() LIMIT 1");
$stmt->execute(array(':viewed' => $value));
PDO::execute() only take value in array.
see: http://php.net/manual/en/pdostatement.execute.php
Probably thats due to the $value param itself. PHP is a loosely typed language
$stmt = $conn->prepare("SELECT * FROM images where id NOT IN (:viewed) ORDER BY rand() LIMIT 1");
$stmt->execute([':viewed' => $value]);
// Here $value is something not evaluated
Instead, do this
$valueArr = $value.explode(",");
$notIn = "";
for($i=0; $i<$valueArr.count(); $i++){
$notIn .= $valueArr[$i]
}
$stmt = $conn->prepare("SELECT * FROM images where id NOT IN (:viewed) ORDER BY rand() LIMIT 1");
$stmt->execute([':viewed' => rtrim($notIn), ","]);
I have got 2 tables; table1 and table2. Both of them are related to eachother with a common groupid I am able to query the second table successfully using the following code:
$query = $this->db->query("SELECT * FROM `table2` WHERE `memberid`='$id'");
$data['relation'] = $query->result_array();
Now using groupid result I want to query the first table i.e. table1
I have tried the following methods, without any success:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
}
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 1 ideally should be 2
The above code only returns the last row of the table1 however I am looking for all the results.
When I run the above code inside the "for" loop, it shows me a count of 33:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 33 ideally should be 2
}
I know how to achieve this in core php however not too sure how to do it in CI. I am new to CI, any help will be greatly appreciated.
Thanks,
Utpal
$ok = array();
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
print_r ($id);
echo "<br>";
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'][$ii]= $query1->result_array();
}
//print_r($data1['group']);
$fine = array_merge($data, $data1);
print_r($fine);
You need to create a array ($data1) outside this for loop and define $query->result_array(); inside forloop as shown above
Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";
The table_calc structure (minimized) is:
| id | value_1 | value_2 |
the number of rows is between 70 and 250 or more.
I want to update the fields in "table_calc" with values resulting from other calculations ($value_update_1 and 2, ...), values applied different to the fields in the table.
Before I used a table on the web page and from there I updated the table.
Now I want to update the values directly without having to take them in the page, as it should work.
I started to write the code below:
$stmt_update = $conn_bd->prepare('select * from table_calc');
$stmt_update->execute(array());
$result_stmt_update = $stmt_update->fetchAll();
foreach($result_stmt_update as $rrows_update) {
$cal_id = $rrows_update[id];
$cal_value_1 = $rrows_update['value_1'];
$cal_value_2 = $rrows_update['value_2'];
}
$value_update_1 = 100.25;
$value_update_2 = 150.25;
$count_id = count($cal_id);
$stmt = $conn_bd->prepare('UPDATE table_calc SET value_1 = :value_1, value_2 = :value_2 WHERE id = :id');
$i = 0;
while($i < $count_id) {
$stmt->bindParam(':value_1', '.$cal_value_1[$i].' * '.$value_update_2.');
$stmt->bindParam(':value_2', '.$cal_value_2[$i].' * '.$value_update_1.');
$stmt->bindParam(':id', $cal_id[$i]);
$stmt->execute();
$i++;
}
but it doesn't work
Can you help?
I can spot a few issues on your code:
On line 8:
$cal_id = $rrows_update[id];
^^
You need quotes there.
On line 20, you call your variable as if it were an array, but you don't set it as such on lines 9-10.
Again on line 20, you should bind the final value to the parameter, not leave it to be evaluated by MySQL.
So the corrected version would be:
$stmt_update = $conn_bd->prepare('select * from table_calc');
$stmt_update->execute(array());
$result_stmt_update = $stmt_update->fetchAll();
foreach ($result_stmt_update as $rrows_update) {
//Added array push operators. To make them arrays.
$cal_id[] = $rrows_update["id"];
$cal_value_1[] = $rrows_update['value_1'];
$cal_value_2[] = $rrows_update['value_2'];
}
$value_update_1 = 100.25;
$value_update_2 = 150.25;
$count_id = count($cal_id);
$stmt = $conn_bd->prepare('UPDATE table_calc SET value_1 = :value_1, value_2 = :value_2 WHERE id = :id');
$i = 0;
while ($i < $count_id) {
//Altered the binding so that you bind the final value.
//Also changed to bindValue.
$stmt->bindValue(':value_1', $cal_value_1[$i] * $value_update_2);
$stmt->bindValue(':value_2', $cal_value_2[$i] * $value_update_1);
$stmt->bindValue(':id', $cal_id[$i]);
$stmt->execute();
$i++;
}
Also, when making batch changes to the database, you may want to use Transactions, to make sure all changes are registered as expected.