PHP MySQLi echo data in array without doing a while loop - php

When using MySQLi, do I have to perform a kind of while loop where the actual data from the query is put into a variable array?
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// Check if able to connect to database
if ($conn->connect_error) {
trigger_error("Database connection failed: " . $conn->connect_error, E_USER_ERROR);
}
$sql = "SELECT name FROM users WHERE email = '$email'";
$rs = $conn->query($sql);
$numRows = $rs->num_rows();
I always do the following:
$rs->data_seek(0);
while($row = $rs->fetch_assoc()) {
$name = $row['name'];
}
echo $name;
Isn't there a much more convenient way to echo the data form the query when there is only one row?

If there is only one row, you don't need the loop. Just do:
$row = $rs->fetch_assoc();
$name = $row['name'];

Related

Selecting Data from SQL Database Returns "1"

This is my first SQL Database. I've been able to successfully connect to my server and database. But, when I use a query to select data from one of the columns in my table, it returns the number "1". Why is this?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Item FROM Items";
$result = $conn->query($sql);
echo "<h1>Connected successfully<h1>";
echo "<p class='lead'>" + $result + "</p>";
$conn->close();
?>
Here's an image of the table named Items
This is what shows up on the webpage where it should echo the contents in the item column:
You're just echoing the whole object, not individual rows. You need to do something like this to iterate over each row.
if ($result = $conn->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
echo "<p class='lead'>" . $row[0] . "</p>";
}
/* free result set */
$result->close();
}
This is because 2 different things:
You are trying to concat a string with the + simbol not with the . simbol.
Your $result variable contains a mysql_result, because the query was executed.
If you want to echo your data you must to use $result into a while loop.

Adding different values together from same table

I have a table. In that table, there is are two fields called to and amount. I need to display the sum of amount of all rows where to value is equal to a particular value. (Say 34). How to achieve this?
Code I have done so far
$result = mysql_query("SELECT * FROM transactions WHERE to = '34'")or die(mysql_error());
while($row = mysql_fetch_array( $result )) { echo $row['amount']; } ?>
The above code gives the individual amount value of each row. But what I want is the sum of these values.
The Database
Use SUM to add all the amounts and echo it
$result = mysql_query("SELECT SUM(amount) as amounts FROM transactions WHERE to = '34'")or die(mysql_error());
while($row = mysql_fetch_array( $result )) { echo $row['amounts']; } ?>
I suggest you to use mysqli_* or PDO because mysql_* is deprecated and not available in PHP 7.
Here is the complete example of your code by using MYSQLi Object Oriented:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT SUM(amount) as amounts FROM transactions WHERE to = 34";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['amounts']. "<br>";
}
}
else
{
echo "0 results";
}
$conn->close();
?>

How do I get one row of data from mySQL table using php?

Here is an example of the current PHP code I have. I simply want to grab one row from the table, but it returns this error:
Call to a member function fetch_assoc() on a non-object
Any insight would be appreciated.
$pathname = "C:\Users\BL\Documents\GitHub\Moozik\music";
$files = scandir($pathname);
$server = "localhost";
$user = "root";
$pass = "";
while ($files[0] == "." || $files[0] == "..") {
array_shift($files);
}
print_r($files);
$song = $pathname . '\\' . $files[0];
$conn = new mysqli($server, $user, $pass);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT song_path FROM song_data";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()) {
$its = $row["song_path"];
printf($its);
}
mysqli_close($conn);
Point 1 :
You have mixed mysqli Object-oriented and Procedural methods...Use any one
Point 2:
$conn = new mysqli($server, $user, $pass);
// Here You missed database to be selected
Point 3:
$result = mysqli_query($conn, $sql); // Used procedural method But Connection is by Object Oriented method
here is a full object oriented method
$conn = new mysqli($server, $user, $pass, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT song_path FROM song_data";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$its = $row["song_path"];
echo $its;
}
$conn->close();
You can use
$row=mysqli_fetch_array($result)
You don't even have to use while since you wanna fetch only one row. IF you wanna fetch more than one row, then you can use the while.
You can use this.
$row=mysqli_fetch_row($result)
It will fetches the one row from result set..
Hope this will help.!

Query MySQL with PHP

I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.
Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {

Load mysql result into php variable

Hello I have this code:
<?php $servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT varible FROM test";
$result = $conn->query($sql);
echo $result;
?>
All I want is to load a number from mysql table and load it into php variable and work with that variable as number.
Thanks for any reply.
try this:
$sql = "SELECT varible FROM test";
$result = $conn->query($sql);
$res = mysqli_fetch_assoc($result);
echo $res['varible'];
if you have a list then you can use:
while($res = mysqli_fetch_assoc($result)) {
echo $res['varible'];
}
in the last line do it like this:
$sql = "SELECT varible FROM test";
$result = $conn->query($sql);
$row=$conn->fetch_array($result);
echo $row;
MySQLi::query() returns a MySQLi_Result object for SELECT queries. You should read the documentation.
The MySQLi_Result object has a variety of method that you can use to get at the rows.
If we use e.g. MySQLi_Result::fetch_object() then we can do it like this:
while ($row = $result->fetch_object()) {
var_dump($row);
}
You got it all wrong...think about it one second: if the query returns multiple results how can you store it in one variable?..you need or to loop through the results and assign each time a different value or store the results in an array.

Categories