Selecting Data from SQL Database Returns "1" - php

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.

Related

How to use ? in URL?

I am trying to figure out a way to have one PHP page to display all of my blog post but have the URL decide what post is requested from that database. Something kind of like this: localhost/bolg/posts.php?pid=1 In my database I have it set up to where each post has an ID associated with it. So what I want is something that put the pid=1 and put it in the MySQL code. Here is the PHP code of the post.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title, content, date FROM posts where id =3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Assuming you enter example.com?pid=10 in the browser address bar, you can capture that variable pid using the $_GET (docs) array which PHP automatically fills for you when a page is called with a querystring.
Using your existing code as a start point you can
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
if (isset($_GET['pid'])) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, title, content, date FROM posts where id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['pid']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
// while looop is not necessary, you are only returning one row
$row = $result->fetch_assoc();
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
$conn->close();
} else {
echo "0 results";
}
Notice I took the liberty of amending your database access code to use prepared and parameterised query and binding the values to avoid SQL Injection Attack. You should always use this technique in the future

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();
?>

Getting User Data Based on Their Information

This first field is where a web visitor will enter in the 'cardname' hit submit and be directed to another page (dashboard2.php) where only his or her content will appear.
Enter your cardname to access your content<br>
<form action='dashboard2.php'>
<input type='text' name='cardname'/><input type='submit' value='retrieve card'/>
</form>
</body>
The page below is the page that is directed after the user enters in the 'cardname' from the first input field. However, I only want this second page to show the information based on the cardname that was entered. Right now, it shows every single cardname, questionone, answerone from that table.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
You have to modify the query to accept a WHERE clause. For instance, WHERE cardname = mysqli_real_escape_string($conn, $_GET['cardname']) (The default method for any form is GET unless you specify method="post".).
You should learn about prepared statements for MySQLi and perhaps consider using PDO, it's really not hard.
It seems that you want to perform a search and not a display all the records.
Usually a search returns records that match a certain field, unless a specific ID or unique value was entered in the search. I'm not sure this is the case.
I put this together a little quick but hopefully it helps...
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// escape the string to avoid SQL injections
$searchEscaped = $conn->real_escape_string($_POST['cardname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards WHERE cardname = '$searchEscaped' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($result->num_rows == 1){
// only one result found, show just that
$row = $result->fetch_assoc()
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}else{
// multiple rows found, show them all
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
?>

mysqli create link based on row

I want to create an link based on row value, AND - MORE IMPORTANT, add an variable - if row empty, then this text... if row have some value, display this....
//I NEED TO GET THIS DISPLAY:
// if row season is empty, the resulting link must be
// web.com/MOVIES/".$row["title_id"]."
// if row season have some value, then the link must be: //web.com/SERIES/".$row["title_id"]."/SEASON/".$row["season"]."/EPISODE/".$row["episode"]."
This is the base code.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, label, title_id, season, episode, approved FROM links order by id desc LIMIT 30 OFFSET 50";
$result = $last_id = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>ID</th><th>Label</th><th>URL</th><th>Season</th><th>Episode</th><th>Approved</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
// --------------------------------------------------------------
echo "<td><a href='http://web.com/(VARIABLES HERE)'>";
echo " ".$row["title_id"]."</a></td>";
// --------------------------------------------------------------
//I NEED TO GET THIS DISPLAY:
// if row season is empty, the resulting link must be
// web.com/MOVIES/".$row["title_id"]."
// if row season have some value, then the link must be:
//web.com/SERIES/".$row["title_id"]."/SEASON/".$row["season"]."/EPISODE/".$row["episode"]."
// -----------------------------------------
echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
As is stated in the comments, you are using a reserved MySQL keyword: type. So your query is not working properly. You can't tell because you haven't set up any checks to make sure it is working. you can either put backticks around it like so:
SELECT id, `type`
or change the name of the key in your database (I'd recommend this approach, something like titleType). Until you fix this, nothing will work in your PHP.
Once you have fixed this, as for how to generate your results, you could do something like this inside your while loop (I'm assuming your mean the episode value):
if (empty($row['episode'])) {
echo 'web.com/MOVIES/'.$row["title_id"];
}
else {
echo 'web.com/SERIES/'.$row['title_id'].'/SEASON/'.$row['season'].'/EPISODE/'.$row["episode"];
}
THIS IS THE CORRECT FULL CODE.
<?php
$servername = "localhost";
$username = "WRITE YOUR DB username ";
$password = "WRITE YOUR DB password";
$dbname = "WRITE YOUR db name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, label, title_id, season, episode, approved FROM links order by id desc LIMIT 30 OFFSET 1";
$result = $last_id = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>ID</th><th>Audio</th><th>URL</th><th>Temporada</th><th>Episodio</th><th>Aprobado</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
echo "<td><a href=";
if (empty($row['episode'])) {
echo '/peliculas-online/'.$row["title_id"];
}
else {
echo '/series-online/'.$row['title_id'].'/seasons/'.$row['season'].'/episodes/'.$row["episode"];
}
echo ">".$row["title_id"]."</a></td>";
echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

PHP MySQLi echo data in array without doing a while loop

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'];

Categories