print a value from a select statement in PHP - php

All I am trying to do is display the price of an item from an mysql database in an <h1> tag. Nothing fancy or difficult. I have a page that has 60 item on it, and I need to update prices on our database 2 to 3 times a year. This would keep this page consistent with the database.
I have establish a standard mysql connect. I have defined a variable from a select statement. Now I just need to know how to display the info. when I run this php, I get an error "Notice: Undefined variable: products in /Applications/MAMP/htdocs/staging/dynamic_mixers.php on line 123"
Below is my code.
$products = "SELECT Base_Price FROM products Where record_number=1072;
echo "<h1>'.$products['Base_Price'].</h1>

In php, you write the query:
$products = "SELECT Base_Price FROM products Where record_number=1072"; //don't forget end quote
You make a connection to the database like this:
$connection = new mysqli("localhost", "user", "password", "database");
Then you send the query to be processed using the connection, like this:
$results = mysqli_query($connection, $products);
Then you need to loop through the results (even if there is only one)
while ($row = mysqli_fetch_assoc($result)) {
}
In that loop you can access $row['Base_Price']
while ($row = mysqli_fetch_assoc($result)) {
echo $row['Base_Price']
}
Read more about it here: PHP and MySQL

I prefer to use PHP data Objects over mysqli. Better performance and less chance of being susceptible to injection attacks.
// setup the query
$dbh = new PDO
(
'mysql:host=localhost;dbname=myDatabase',
$username,
$password,
array
(
PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC
)
);
$query = $dbh->Prepare('SELECT Base_Price FROM products Where record_number=? LIMIT 1');
// execute for one item
$query->execute(array(1072));
$singlePrice = $query->fetch();
// execute for the next item
$query->execute(array(1073));
$singlePrice = $query->fetch();
// execute for the third item, etc
$query->execute(array(1074));
$singlePrice = $query->fetch();
You can throw all of the executes in a for loop and get maximum performance since PDO is using a prepared statement.

Related

What is the best method to use when assigning a numerical value from a mySQL database to a PHP variable?

I'm attempting to grab a number value from a mySQL database using PHP. I'd like to use that number value for some calculations after I've assigned it's value to a variable. The number value is stored as a float in my database. My code attempts to connect to my database (which it does successfully), then pull a number value based on parameters passed on by my query, then apply that number value to a variable that I can use in my code. In my code below, I'm simply trying to print that value to make sure it's pulling properly. The result I get is this notice: Notice: Array to string conversion in /Users/max/Desktop/Sites/webprojects/prg/nba/percentchange.php on line 14 Array
Here's my code:
$mysqli = new mysqli('localhost', 'root', 'root', 'NBA');
if (mysqli_connect_errno()) {
echo '<p>Error: could not connect to database.</p>';
exit;
}
$rank = "SELECT average FROM nbaCompRankings WHERE team = 'Celtics'";
$result = $mysqli->query($rank);
$currentRank = $result->fetch_assoc();
echo $currentRank;
The potential solutions I've found on this site use deprecated libraries, so I've been unsuccessful in a search for a solution. Thanks in advance for any help you can give!
Try This:
$result = $mysqli->query($rank);
while($row = $result->fetch_assoc()) {
$currentRank = $row["average"];
}
You should really be preparing your statements though.
$team = 'Celtics';
$sql= "SELECT average FROM nbaCompRankings WHERE team = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $team);
$stmt->execute();
$stmt->bind_result($average);
while($stmt->fetch()) {
$currentRank = $average;
}
$stmt->close();

How to retrieve one row/one field using PHP mysql_fetch_array

Just started learning PHP, Angular and mySQL and am trying to retrieve just one field value from one single row. The same code below works for a query that returns multiples rows:
$qry = "SELECT ID FROM SharePoint001 ORDER BY DownloadedTimeStamp DESC LIMIT 1"; //returns a5f415a7-3d4f-11e5-b52f-b82a72d52c35
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array("ID" => $rows['ID']);
}
print_r(json_encode($data[0]));
I highly recommend switching to the mysqli extension. It's a much better way of doing things and you will probably find it much easier.
Here's a simple mysqli solution for you:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();
If you're grabbing more than one row, I do it like this:
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With Error Handling: If there is a fatal error the script will terminate with an error message.
// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.
try {
if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) throw new Exception($db->error);
while ( $row = $resource->fetch_assoc() ) {
echo "{$row['field']}";
}
$resource->free();
$db->close();
} catch (Exception $e) {
echo "DB Exception: ",$e->getMessage(),"\n";
}
The MySQL extension is:
Officially deprecated (as of PHP 5.5. Will be removed in PHP 7.)
Lacks an object-oriented interface
Much slower than mysqli
Not under active development
Does not support:
Non-blocking, asynchronous queries
Transactions
Stored procedures
Multiple Statements
Prepared statements or parameterized queries
The "new" password authentication method (on by default in MySQL 5.6; required in 5.7+)
Since it is deprecated, using it makes your code less future proof. See the comparison of SQL extensions.
You have not executed the query, so you'll never get results.
First you have to prepare query and place it into a variable lets say $qry.
Then execute that query by using mysql_query() function and capture result into a variable lets say $result
Now you can iterate that $result with loop to fetch rows and cells (what you call fields).
Below is code I have corrected:
$qry = "SELECT ID FROM SharePoint001 ORDER BY DownloadedTimeStamp DESC LIMIT 1";
$result = mysql_query($qry); // You are missing this line
$data = array();
while($rows = mysql_fetch_array($result)) // You have to pass result into mysql_fetch_array not query string
{
$data[] = array("ID" => $rows['ID']);
}
print_r(json_encode($data[0]));

Randomly access to rowset/resultset with PDO Mysql and PHP

I want to access randomly to a result sets retuned from a Stored Procedure using PDO Mysql and PHP. I found PDOStatement::nextRowset but the access to the result sets seems to be sequential.
EDIT
I'm looking for some like this:
$pdo = new PDO("mysql:host=$server;port=$port;dbname=$dbname;charset=utf8", $user, $pass, array(PDO::ATTR_PERSISTENT => false));
$statement = "CALL FooSP()";
$query = $pdo->prepare($statement);
$query->execute();
$query->resultSet[1][0]["ColumnFoo"] // Second Resultset, first row, column "ColumnFoo"
$query->resultSet[3][1]["ColumnBar"] // third Resultset, second row, columna "ColumnBar"
$query->resultSet[0][0]["Column1"] // first Resultset, first row, columna "Column1"
Can anyone help me?
If You need all resultsets - just prefetch them using next rowset like this:
<?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn->query($sql);
$fetched_rowsets = array();
do {
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset)
{
$fetched_rowsets[] = $rowset;
}
# This is important part.
} while ($stmt->nextRowset());
#Now You got the table with all data from all resultsets, fetched in PHP memory.
$fetched_rowsets[1][0]["ColumnFoo"];
$fetched_rowsets[3][1]["ColumnBar"];
$fetched_rowsets[0][0]["Column1"];
?>
Just remember that it can be memory consuming.

Querying database with php

I am trying to query my database using php, to then display the results of the query. For this example, I only want the number of elements in my MySQL database.
My code is:
<?php
print("This is just a test");
print("This is another test");
// Create connection
$con=mysqli_connect("mysql.netsons.com","****","****","****");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
print("A third test");
$result = mysqli_query($con, "SELECT COUNT(*) FROM MyGames");
echo $result;
echo mysqli_fetch_array($result);
print("A forth test");
mysqli_close($con);
?>
This is the result:
This is just a testThis is another testA third test
What am I doing wrong?
mysql_fetch_array fetches ... an array.
$row = mysqli_fetch_array($result);
echo $row["COUNT(*)"];
I think it would be better to alias that column too:
SELECT COUNT(*) AS count FROM MyGames
...
echo $row['count'];
I would recomend using a diferent method of querying that is much safer(As far as I know there is no SQL Injection to worry about) and it saves a lot of time and space.
First you need to create an mysqli object
$stateConnect = new mysqli("localhost", "root", "PASS", "DBTable");
This does the same thing as mysqli_connect and mysqli_select_db
Then you want to define your SQL query
$sql = "SELECT `userVotes` FROM `users` WHERE `userEmail`=?";
Next you want to create a variable called a statement with your SQL "attached to it"
$statement = $stateConnect->prepare($sql);
Notice how in my SQL I didn't directly put the value required for userEmail, instead I put an '?'. This acts as a variable that we will later define(However it will always be a '?'
To define this variable we need to use.
$statement->bind_param('s', $SESSION['email']);
This binds $SESSION['email'] to the first qustion mark, the s is saying that the first question mark will be a string. Lets say we had to varribles:
$sql = "SELECT `userVotes` FROM `users` WHERE `userEmail`=? AND `userName`=?";
We would then use:
$statement->bind_param('ss', $SESSION['email'], "USERNAME");
Each s replresents a question mark and each value after that represents a question mark.
Now we have to execute our query with.
$statement->execute();
If we are expecting a result to be returned then we have to use
$statement->bind_result($userVotesText);
To bind the results to a variable, If I was expecting to columns of results I would need to put a second variable in.
Now to set those varribles we need to use
if($statement->fetch()){
$userVotesResult = userVotesText;
}
This method is much better than other for querying databases and is called Prepared Statement

Loading MySQL data into a PHP array

I am trying to load a list of IDs into a PHP array which I can loop through. The SQL query I am using returns 283 rows when I run it in PHPMyAdmin. However, when I run the following PHP script, it only returns a single row (the first row). How can I modify my code to include all the rows from the resulting SQL query in my PHP array?
Code:
//Get active listing IDs
$active = "SELECT L_ListingID FROM `markers`";
$active = mysql_query($active) or die(mysql_error());
if(is_resource($active) and mysql_num_rows($active)>0){
$row = mysql_fetch_array($active);
print_r($row);
};
Thanks,
Using mysql_fetch_array will return only the first row and then advance the internal counter. You need to implement it as part of a loop like the following to get what you want.
while($row = mysql_fetch_array($active)) {
// Your code here
}
Keep in mind that mysql_ functions are now also deprecated and slated to be removed in future version of php. Use mysqli_ functions or PDO.
In PDO it's rather straight forward:
$rows = $conn->query($active)->fetchAll();
See PDO::queryDocs and PDOStatement::fetchAllDocs.
With mysqli you would use mysqli_result::fetch_all and with PDO there's PDOStatement::fetchAll to fetch all rows into an array.
Code for mysqli
$sql = "SELECT L_ListingID FROM `markers`";
$result = $mysqli->query($sql);
if ($result !== false) {
$rows = $result->fetch_all();
}
with PDO it's nearly the same
$sql = "SELECT L_ListingID FROM `markers`";
$result = $pdo->query($sql);
if ($result !== false) {
$rows = $result->fetchAll();
}

Categories