What is the difference between the two? (query select and display result) - php

I am trying to understand what the difference is between these two lines of code.
I have two pages ACR.php and webPage1.php. ACR.php is included on any page I need to have a database connection. The goal is to obtain the value from the database and display it on the webpage.
// ACR.php //
<?php
// Est. Connection
$dbc = mysqli_connect($ACR_host, $ACR_user, $ACR_pass, $ACR_tablename)
or die('Error communicating to MySQL server');
// Select value from row in table
$thisPort = $dbc->query("SELECT activePort FROM table1 ")->fetch_row()[0];
// Select value from row in table
$thatPort = "SELECT activePort FROM table1";
// Displays result
$result1 = mysqli_query($dbc, $thisPort);
$result2 = mysqli_query($dbc, $thatPort);
?>
webpage1.php will not display the correct value when echoing $result1 but rather echo 'result not found'.
// webPage1.php //
<?php include 'ACR.php';?>
<!--html-->
<tr>
<th>Port<span id="portDisplay"></span><sup></sup>:</th>
<td id="showPort" style="text-align:left;width:75%;">
<?php
session_start();
if (mysqli_num_rows($result1) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result1)) {
echo " " . $row["activePort"];
// echo $row;
}
} else {
echo "result not found";
}
mysqli_close($dbc);
?>
</td>
</tr>
However, if I echo in $result2, the correct value displays from the database table.
Why is this? What makes this so? Are not both $thisPort and $thatPort calling the same row in the table?
UPDATE: I use $thisPort, in part, when fetching a local and remote address. So i would prefer using the current syntax for $thisPort as it works but changing it to the syntax of $thatPort crashes the page. Why is it the value can be pulled from the Database when using this method, but not when i need to display the port on the page.
I don't want to initiate an extra variable ($thatPort), if I don't have to, to simply echo the value from the database when the original var ($thatPort) should and is already doing this.

$thisPort already contains a row from the database. This is not a valid argument to supply to mysqli_query. If you look at your php error log, you'll probably see (depending on your log settings) that the line $result1 = mysqli_query($dbc, $thisPort); generates an error message; $result1 will actually contain FALSE.
$thatPort contains a SQL query string, which is a valid argument to the mysqli_query function, and creates a valid result set in $result2.

Related

php sql not deleting row even showing success

I am trying to delete a row using a href, it's not showing the error but it's not delete the row from my table either. Not sure what i'm doing wrong.
delete.php
require_once "db.php";
$id = $_GET['id'];
$sql = "DELETE FROM books WHERE isbn = ". $id;
if (mysqli_query($db, $sql)){
echo "Success";
}else{
echo "Error";
}
main.php
if($resultSet->num_rows > 0){
while($rows = $resultSet->fetch_assoc()){
$au = $rows['author'];
$bt = $rows['booktitle'];
$rev = $rows['reserved'];
echo"<tr><td>$au</td><td>$bt</td><td>$rev</td><td><a href='delete.php?id=".$rows['isbn']."'>Delete</a></td></tr>\n";
}
echo"</table>";
}
I used a back quote (`) around the field name and it is OK now.
Example:
DELETE FROM table WHERE `field_name` = something
It seems like if you're getting the success message then the query ran successfully, which means that the database connection established OK so we can rule that out.
I think that your query is running but not finding any match on the ISBN so the record isn't getting deleted. I would try echoing out the actual SQL query just before execution so you can then copy it, connect to the database and then paste that query in to run yourself. Maybe change it to a SELECT statement first so you can see if it actually gets the row for deletion. If not then a row with that ISBN either doesn't exist or you've got something strange like an extraneous space/other weird character in the ID somewhere.

Data Management Issue - How to manage retrieved data from mysql?

I am developing a game(c#) with database(mysql) and web service(php) to retrieving the data. The issue is the data management. There is a table on database with the name of items and it has some columns like id, item_name, item_description, item_prop, update_date, ownerId. I added 70 items to this table manually. The users can also add some items to this table or they can update the items they have already added in the game. My purpose is retrieving the whole affected rows of the table when the user is first logged in and save it as a json file in the game folder. After, read that file to fill the game environment with those items.
I try a way to achieve this. Firstly, i hold an updateDate variable in the game which is past like "1990-05-10 21:15:43". Second, i send this variable to the webservice as '$lastUpdateDate'; and make a query according to that variable at the database. select * from channels where update_date >= '$lastUpdateDate'; and write these rows in a json file as items.json. after that make a second query to retrieve the time and refresh the updateDate variable in the game. select select now() as 'Result';. In this way user would not have to get the whole table and write in json file every login process. So, it would be good for the performance and the internet usage. The problem occurs when the users update an item which is already added before. I can see the updated item, too with the first query, but I wrote it in json file twice in this way.
php code part of the getItems of my loginuser.php :
<?php
include './function.php';
// CONNECTIONS =========================================================
$host = "localhost"; //put your host here
$user = "root"; //in general is root
$password = ""; //use your password here
$dbname = "yourDataBaseName"; //your database
$phpHash = "yourHashCode"; // same code in here as in your Unity game
mysql_connect($host, $user, $password) or die("Cant connect into database");
mysql_select_db($dbname)or die("Cant connect into database");
$op = anti_injection_register($_REQUEST["op"]);
$unityHash = anti_injection_register($_REQUEST["myform_hash"]);
if ($unityHash == $phpHash)
{
if($op == "getItems")
{
$lastUpdateDate = anti_injection_login($_POST["updateDate"]);
if(!$lastUpdateDate)
{
echo "Empty";
}
else
{
$q = "select * from items where update_date >= '$lastUpdateDate';";
$rs = mysql_query($q);
if (!$rs)
{
echo "Could not successfully run query ($q) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($rs) == 0)
{
echo "No rows found, nothing to print so am exiting";
exit;
}
$arr = array();
while ($row = mysql_fetch_row($rs))
{
$arr = $row;
}
echo json_encode($arr);
}
mysql_close();
}
}
?>
So, how can i solve this problem? Or do you have any better idea for this approach. Help would be much appreciated. Thank you for your time.

How to dynamically populate new page with variable set on last page?

I'm new to PHP and am trying to build my a website to display information on TV shows stored in a MySQL DB. I've currently got a webpage that will create a table to display the information in the DB, however I'd like each row to link to a dynamically populated page with more info on each show (also pulling from the DB). My question is how do I get the site to know which link has been clicked and then save that as a variable so it can then be recalled on a new to populate the correct information?
I'm currently using this to populate the page.
<!--Populate page with data from SQL-->
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "media_server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th></th><th></th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>
<img src='../images/thumbnails/tv/".$row["thumbnail_path"]."'>
</td>
<td class='td_title'>
<a href='#' onclick='show_var_set();'>".$row["show_title"]."</a>
</td>
<td class='td_desc'>".$row["show_desc"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "Error - 0 results were returned my the database. Please try again.";
}
$conn->close();
?>
One option is to change your href links to point to this page and pass a GET variable you can retreive. The added bonus to this approach is you could bookmark a particular show and come back to that page, since the bookmark will include that GET variable.
So you could change your links to something like this:
echo '', $row['show_title'],'';
Then you'd retrieve that variable by testing for, then reading the GET variable and performing a db query to populate the page with that show's data.
Here's how you'd test for and retreive that variable:
if (isset($_GET['show']))
{
$show = $_GET['show'];
// Perform database lookup using $show
}
Remember to never put user input directly into a query, but use prepared statements and bind the user data to avoid the risk of SQL injection.
There are many ways to pass values from page to page but one is to use session variables:
//Include this at the top of your php scripts that use session variables
session_start();
$_SESSION['your_variable_name_here'] = value_you_want_to_store;
Then on the page you would like to access this use:
$someVariable = $_SESSION['your_variable_name_here'];
Change the SQL to return the show_id,
$sql = "SELECT show_id, show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
and use that as a parameter to the show_var_set() function.
<a href='#' onclick='show_var_set(".$row["show_id"].");'>".$row["show_title"]."</a>
The show_var_set() function can then use that parameter to get the details for that show from the database.

Fastest way to get MySQL cell data as a string?

I want to take the value of a single MySQL cell and use it as a string inside PHP code - I already know the cell exists, where it is, and nothing else is needed. What's the easiest way to do this? All the examples I've found focus on using a loop to output multiple rows into a table, which seems needlessly complicated for my purposes.
Basically what I want to do is this:
require_once 'login.php'; // Connects to MySQL
$sql = "SELECT name FROM users WHERE id='1'"; // id is determined elsewhere
$result = mysqli_query($connect, $sql);
echo "Your name is " . $result;
But I get an error message that it's not a valid string.
You forgot to fetch record from $result using mysqli_fetch_assoc().
So you can fix your code this way:
$result = mysqli_query($connect, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "Your name is " . $row['name'];
}

Session variables in PHP

Hey guys, Im doing a series of if statements based on a session variable that is set (which looks at a value in the DB and then decides whether to empty the session, or name it. However I'm having problems in that the session is always named, regardless of whether the record in the database is '0' or not. The query works fine when run in mysql. Here's the code:
session_start();
$_SESSION['MemberType'] = '';
mysql_select_db($database_choices, $choices);
$query = "Select lifemember from registrants where username = '" . $_SESSION[kt_login_user] . "'";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
while($row = mysql_fetch_array($result))
{
if ($row['lifemember'] == '1')
{
$_SESSION['MemberType'] = 'LifeMember';
}
else if($row['lifemember'] == '0')
{
$_SESSION['MemberType'] = '';
}
}
Precheck: If you are getting any 'Headers already sent...' then you have some output already on the page which is preventing the setting of session.
Otherwise try debugging steps like:
1) Do an echo $row['lifemember'] inside the while loop so that you know REAL value of what's been fetched from DB.
2) In else block, change it to $_SESSION['MemberType'] = 'Hello'; Then see, whether Hello is printed or not?

Categories