PHP: make sessions from database - php

I am trying to make some sessions from my database.
What I wan't to do is, take a specific row in my database an add the value of each column to a session.
The name of the session should then be the name of the column.
I am running ´session_start();´
Here is the code and my attempt to do it:
function opponent_data(){
try {
$PDO_new = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
$PDO_new->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$opponent = $PDO_new->prepare("SELECT * FROM Info WHERE user_name =:username");
$opponent->bindParam(":username", $_SESSION["opponent"]);
$opponent->execute();
//my failed attempt
$row = $opponent->fetch(PDO::FETCH_ASSOC);
$column = $opponent->fetch(PDO::FETCH_COLUMN);
$col_count = $opponent->columnCount();
for ($x = 0; $x <= $col_count; $x++) {
$_SESSION[$column[$x]] = $row[$x];
}
}catch (PDOException $e) {
$error[] = $e->getMessage();
}
}
Thanks for any help.
Sorry for the bad tittle, I didn't knew what i should call this.

When you use PDO::FETCH_COLUMN a column number is expected ie.:
$stmt->fetch(PDO::FETCH_COLUMN, $number_of_column);
It would be easier to loop through the columns from your PDO::FETCH_ASSOC
$row = $opponent->fetch(PDO::FETCH_ASSOC);
foreach ($row as $columnName => $columnVal){
$_SESSION[$columnName] =$columnVal;
}

$x is a number... But you are fetching your result into an associative array. $row[$x] subsequently does not exist.
fetchColumn() and fetchAssoc() returns only 1 column... These should be in while-loops...

Related

How to count rows in a while loop using pdo fetch

I was using mysqli_fetch_array and the counting was right until I changed to fetch(), which now only returns the total number of rows instead of returning each number for each row.
So for row one, I want to echo "1", and so on.
NEW NOTE :Everything else inside the while statement is returning correct values, except the counter which returns the total number of rows whereas I want a row number in the order that it was selected from the sql statement.
As requested. This is my connection.
I don't know if i'm suppose to be checking " $e->getMessage();" on every query since I'm using this connection for all my queries.
try {
$dbh = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8', 'usr', 'pwd',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
} catch (PDOException $e){
echo $e->getMessage();
}
This worked
$query = mysqli_query($con, 'SELECT * FROM music');
$count = 0;
while($row = mysqli_fetch_array($query)){
$count++;
echo $count;
}
The new doesn't work.
$query = $dbh->query('SELECT * FROM music');
$count = 0;
while($row = $query->fetch()){
$count++;
echo $count;
}
Works fine, use a try catch do see if your PDO connection is working.
try {
$dbh = new PDO('mysql:host=localhost;dbname=db', 'root', 'root',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sql = 'SELECT * FROM music';
$sth = $dbh->query($sql);
$count = 0;
while($row = $sth->fetch()){
$count++;
echo $count;
}
I've just tested this and it works fine. Either your PDO connection is incorrect or your query returns no results. I suggest you var_dump($dbh) and see if it returns a PDO object or check that your query is correct. Is your table called music? It is case sensitive.
You also need to change your connection form mysqli to PDO
$mysqli = new mysqli("localhost", "user", "password", "database");
to
$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password');
You can also throw PDO exceptions to see if any are occuring:
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
$conn->exec("SET CHARACTER SET utf8");
http://coursesweb.net/php-mysql/pdo-select-query-fetch
What about:
if ($pdo){
$query=$pdo->prepare("SELECT count(*) as cnt FROM music");
if($query->execute()){
$count = $query->fetch()[0];//or fetch()['cnt']
echo $count;
}
}
PDO have a little different behavior. This is a replacement for your mysqli.
try {
$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password',array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// optional
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
));
$count = 0;
foreach ($dbh->query("SELECT * FROM `music`") as $row) {
$count++;
echo $count;
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
exit();
}
I hope that helped.
Try using PDO::FETCH_NUM to get the row count directly :-
$countquery = $dbh->query('SELECT COUNT(1) FROM music');
$rowCount = 0;
$rowCount = $countquery ->fetch(PDO::FETCH_NUM);
echo $rowCount;
//And then do another query for the real data if need be
* This makes use of a query to get the row count, and saves you the time taken by the while loop.

returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?
You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);
You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

how to acess my database elements using the for loop?

I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];

Two Dimensional arrays and both indexes

I have data coming from a query and loading it into a 2 dimensional array inside a loop.
I have the below code but when it prints out the array the index is missing.
How do I load a 2 dimensional aray with the first index being the $id value and second index being the $UserEmail and then how would I loop through the array to pull out each index ($id, $UserEmail)?
//the query
$query = "select id, UserEmail from User";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$ue = $row['UserEmail'];
$id = $row['id'];
if (strpos($ue,','))
{
$UserArrayEmail = explode(',',$ue);
foreach ($UserEmailArray as $u)
{
$ArrayTerm[$id][] = $u;
}
}
}
//looping through the array and getting value from $id and $UserEmail
foreach( $ArrayTerm as $ArrayT ) {
print_r($ArrayT);
foreach( $ArrayT as $value ) {
echo $value . "<br/>";
}
}
Please help.
mysql_connect() is deprecated your solution should use PDO instead.
This is how it could be done with PDO and will fix the indexes:
//fetch array from query
try {
$dbh = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
} catch (PDOException $e) {
// db error handling
}
$sth = $dbh->prepare("select id, UserEmail from user");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
while($row = $sth->fetch())) {
$emails = $row['UserEmail'];
$id = $row['id'];
if (strpos($emails,',')) {
$UserEmailArray = explode(',',$emails);
foreach ($UserEmailArray as $email) {
$ArrayT[$id][] = $email;
}
}
}
//repeat the same but with PDO data with other loops
}
Additionally, storing a list of data (in your case emails) in a single db column is not great for db normalization.
You have no type safety (VARCHAR can containanything), no referential integrity, no way of actually processing the data with the db (in SELECTs, JOINs etc).
For the db, the list of email addresses is just a bunch of random characters.
The relational database model has a simple rule: one attribute, one value. So if you have multiple values, you have multiple rows. That's what you should fix first. You'll need another table named "user_email_addresses" or something.
With this new table it could be something like:
function html_escape($raw) {
return htmlentities($raw, ENT_COMPAT , 'utf-8');
}
function log_exceptions($exception) {
echo $exception->getMessage(), '<br />', $exception->getTraceAsString();
}
set_exception_handler('log_exceptions');
$database = new PDO( 'mysql:host=localhost;dbname=DB', 'USER', 'PASS', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION) );
$user_emails = array();
$emails = $database->query('
SELECT user_id , email
FROM user_email_addresses');
foreach ($emails as $email)
$user_emails[ $email['user_id'] ][] = $email['email_address'];
//address list
foreach ($user_emails as $user_id => $email_addresses) {
echo 'User: ' . html_escape($user_id) . '<br />';
foreach ($email_addresses as $email_address)
echo html_escape($email_address) . '<br />';
echo '<br />';

Compare multiple values in two arrays PHP

I have two MySQL Databases, and would like to compare the data using PHP variables. I connect to the databases and assign the variables using PDO:
//Database 1
include_once('client-config.php');
try {
$conn = new PDO(DB_HOST, DB_USER, DB_PASSWORD, array(PDO::ATTR_PERSISTENT => TRUE));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$DB_Name = "pencuy204";
$login = $_SESSION['SESS_login'];
$qry = "SELECT `BetType`, `RiskAmount`, `WinAmount`, `BetDate`, `GameDate`, `BetRotation`, `TeamParticipant`, `MoneyLine`, `Spread`, `OverUnder`
FROM `{$login}_bet`";
$result = $conn->query($qry);
// If the SQL query is succesfully performed ($result not false)
if ($result !== false) {
// Parse the result set, and adds each row and colums in HTML table
foreach ($result as $row) {
$BetType[] = $row['BetType'];
$BetRiskAmount[] = $row['RiskAmount'];
$BetWinAmount[] = $row['WinAmount'];
$BetGameDate[] = strtotime($row['GameDate']);
$BetTeamParticipant[] = $row['TeamParticipant'];
$BetMoneyLine[] = $row['MoneyLine'];
$BetSpread[] = $row['Spread'];
$BetOverUnder[] = $row['OverUnder'];
}
}
//Database 2
try {
require_once('bet-config.php');
$conn1 = new PDO(B_DB_HOST, B_DB_USER, B_DB_PASSWORD);
$conn1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
date_default_timezone_set('CST');
$today = date("Y-m-d");
$qry = "SELECT `AwayTeam`, `AwayScore`, `HomeTeam`, `HomeScore`, `FeedDate` FROM games";
$checkit = $conn1->query($qry);
if ($checkit !== false) {
foreach($checkit as $row1) {
$AwayTeam[] = $row1['AwayTeam'];
$HomeTeam[] = $row1['HomeTeam'];
$AwayScoreData[] = $row1['AwayScore'];
$HomeScoreData[] = $row1['HomeScore'];
$FeedDate[] = strtotime($row1['FeedDate']);
}
}
What I would like to do is run through each value in certain PHP arrays in Database 1, comparing them every value in certain arrays in Database 2. Here is an example for loop that I am working on:
for ($i = 0; $i <= $count; $i++) {
foreach ($BetGameDate as $b) {
if (($b == $FeedDate[$i])) {
foreach ($BetTeamParticipant as $team) {
if (($team == $AwayTeam[$i])) {
foreach ($BetType as $type) {
if (($type == "Money Line")) {
if ($AwayScoreData[$i] < $HomeScoreData[$i]) {
$BetV[] = "-" . $BetRiskAmount[$i];
$BetC[] = intval('$BetV');
}
if ($AwayScoreData[$i] > $HomeScoreData[$i]) {
$BetV[] = "+" . $BetWinAmount[$i];
$BetC[] = intval('$BetV');
}
if ($AwayScoreData[$i] == $HomeScoreData[$i]) {
$BetV[] = 0;
$BetC[] = intval('$BetV');
}
}
}
}
}
}
}
}
In this particular example, if $GameBetDate is equal to $FeedDate, the bet team name is equal to the away team name, and the bet type is equal to a certain string, then compute the bet based on the risk amount or win amount for that specific bet(row) in database 1. I feel like my use of foreach is correct, but how can I properly use an iterated for loop to cycle through all of the values in database 2 against the specific values in database 1, and if the criteria matches, use values from database 1 to calculate $BetC and BetV?
I think you can use a little refactoring in your code.
To compare values you can use array_diff method.
You select the values from the first table, (PDO can return array)
Select second values and compare...
http://php.net/manual/en/function.array-diff.php

Categories