Assistance with PHP and MYSQL - php

I have code here that is supposed to print a html table from my mysql database. When I open the page in my web browser, it is a blank page.
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'admin', 'may122000');
mysql_select_db('contacts');
$query = "SELECT * FROM users";
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysql_close();
?>
</body>
</html>

Remove password
Enable error output
When you use mysql_fetch_array you will get the resulting array with numeric indices.
mysql_fetch_assoc will give you an associative array, like you want.
Note: mysql_* is deprecated.
while($row = mysql_fetch_assoc($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
If you still want to use mysql_fetch_array you'll have to pass a second parameter:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){

First of all user mysqli or PDO and mysqli_fetch_assoc() so you have only associative array. Blank page is probably result of a hidden error, that's stored in your error.log on your server - take a look at it and get back to us.

I prefer using PDO or mysqli but anyway , Are u sure Your connection is established ? to check this and check other connections and query :
if (!connection)
die(mysql_error());
try this and feedback me

Improvements - some of which already mentioned in other post but all put together in one form:
<?php
$connection = mysqli_connect('localhost', 'admin', '****', 'contacts');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first_name, last_name, phone FROM users";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
echo "<table>"; // start a table tag in the HTML
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysqli_close($connection);
?>
So, first off the MySQL_* has been upgraded to Mysqli, with some minor reformatting,
The select * has been replaced with selecting only the needed columns.
The closing statement has been correctly set.
Firstly if your connection fails an error catch will output this to the screen. Remove this upon product launch or public launch of the page.
A (Rather rudimentary) error catch has been put in that if the SQL Query is bad that an error is outputted. Again, this should be removed in production but will help you with finding SQL errors.
If No SQL errors return the you have either an empty table in your database, or some sort of PHP error but from the code sample given the most likely error is that your PHP doesn't run MySQL and would only run PDO or MySQLi.
You also said "when I open the page in my browser it is a blank page", if the Source of the page is blank - as in it DOES NOT show
<html>
etc, then this is a sign the PHP execution failed and you have bad PHP, as detailed in your error log file.
The most likely cause of this from the code sample given is, as stated already, your PHP version does not support MySQL.
If your
<table>
Tag appears in your HTML source code then this is a sign that the While clause is not running which means your Datbase table is empty and there is no data to output.
Hope this helps. But first point of call is to upgrade to MySQLi :)

Related

PHP MySQLi to HTML combobox

I'm trying to pass data from a MySQL database to a HTML combobox and i'm using php to do that
<form method="POST">
<select class="js_inline_input">
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "js_milhoes";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
echo "<option> Connected successfully </option>";
}
$sql = "SELECT * FROM js_country";
$result = $conn->query($sql);
while($row=mysqli_fetch_assoc($result)){
//My Personal echo
echo "<option value='".$row['countryCode']."'>".$row['countryName']."</option>";
//Echo i saw on this site
echo "<option value='{$row->countryCode}'>{$row->countryName}</option>";
}
$conn->close();
?>
</select>
</form>
It should list all the countries in the combobox but what displays is:
- From first echo: ".$row['countryName']."
- From second echo: {$row->countryCode}
I already check the connection, and before i add a if that says that the query is not empty
The reason why your second <option> isn't showing is because you are using a "fetch object" syntax $row->column.
http://php.net/manual/en/mysqli-result.fetch-object.php
You need to use one or the other; not both.
Either you use
while($row=mysqli_fetch_assoc($result)){
echo "<option value='".$row['countryCode']."'>".$row['countryName']."</option>";
}
or (and escaping with double-quotes):
while($row=mysqli_fetch_object($result)){
echo "<option value=\"{$row->countryCode}\">{$row->countryCode}</option>";
}
You also need to note that column names are case-sensitive when iterating over those like that.
Meaning that, countryCode and countrycode are two different animals here, as is countryName and countryname; should it be the case.
Check for errors on your query.
Footnotes:
You state: "but what displays is: - From first echo: ".$row['countryName']." - From second echo: {$row->countryCode}"
I don't understand what you mean by that. I've tested your code and it works fine (besides the "fetch object" syntax issue). If what you mean by that is you are seeing "code" rather than being parsed, then you are either not using a webserver, or that you are accessing it as file:///file.php rather than http://localhost/file.php or as .html should this be the case as the file extension is unknown.
That is my conclusion for this question.
Ok, this was a stupid problem, when i changed from wamp 2.5 to wamp 3 i forget to delete the wwamp paste and i had 2, so i has using the wrong fill and because that one wasn't in a server with apache the browser comments the php

MySQL will not update

This is my first time on SO, so I'm not knowing about everything. I'm sorry. I have a problem with my site. I want to update the viewed status of one of the rows.
This is my update code:
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
$sql= mysql_query ("UPDATE system_reports SET viewed=1 WHERE id =' ".$row['id']." ' ");
$conn->query($sql) or die("Cannot update");//update or error
}
?>
But when I click on the button, I get: Cannot Update. The connection of DB is fine. So I don't know what is the problem. ID is a realy working variable.
So is my rows working:
<?php
function spam_Draw() {
$a = mysql_query("SELECT * FROM system_reports WHERE viewed=0");
while ($row = mysql_fetch_array($a)) {
echo $row['id']." <a href='http://warrock-hack.net/profiel/".$row['user'] . "/'>Gedupeerde</a> <a href='" . $row['report_url'] . "'> Ga naar het probleem toe!</a> " . $row['reason'];
echo '<br>';
echo '<INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"> ';
}
}
?>
I hope someone can help me out! Thanks..
Regards,
John.
Your DB calls are totally wrong. mysql_query() returns a query handle representing the results of your query (or boolean false on failure). You're taking that handle, and feeding it to some OTHER database library.
mysql, mysqli and PDO database handles/results are NOT interchangeable, and the libraries cannot be mixed together like that.
You probably want something more like:
$sql = "UPDATE.... " . $row['id']; // no mysql_query() call, just defining a string
$result = $conn->query($sql);
Plus, die()ing with a fixed string for your error message is utterly useless. The DB libraries can TELL you what the problem was:
$result = $conn->query($sql) or die(mysqli_error()); // assuming mysqli

PHP Query causes SQL Server Tables to disappear and reappear

We have a website that accesses a SQL Server 2005 server for one query. Currently, the site is in ASP, we are moving it to PHP, and the PHP one is currently being tested. After we run a few successful queries on the PHP site, it returns the "Error in database query. Please try again later" line in the code below. When I rewrote that line with sqlsrv_errors to elaborate, it told me that the table didn't exist. There are about 40 tables in the database, but after the error happens it only shows 8 of them in Management Studio. However, if I allow it to sit for about 5 minutes, all of the tables are restored. No matter how many times the old ASP site is used, the table does not do this. However, when the tables disappear from using the new site, the old site shows inaccessible for a few minutes until the tables re-appear in SQL Server management studio. I didn't see any kind of connection limits on the SQL Server, so I don't know whether it's something I'm doing in the PHP SQL queries or within the SQL Server properties.
<?php
include ("dbvals.inc.php");
if (!empty($_POST['lastnamebox'])) {
$dbhandle = sqlsrv_connect($dbServer, $connectioninfo);
if($dbhandle == false){
echo "Error connecting to database. Please try again later. ";
}
else{
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
$params = array();
array_push ($params, $_POST['lastnamebox']);
$results = sqlsrv_query($dbhandle, $query, $params);
if($results == false){
echo "Error in database query. Please try again later.";
//This is printed when database tables temporarily disappear
}
else
{
$row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC);
if($row){
do{
echo "<tr><td class='tablecell'>";
echo $row['LastName'] . "," . $row['FirstName'] . "<br>";
echo "Address: " . $row['Address'] . "<br>";
echo "City, State, Zip: " . $row['CSZ'] . "<br>";
echo "</tr></td'>";
}while($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC));
}
else{
echo "No results found. Please try another query.";
}
}
}
sqlsrv_free_stmt($results);
sqlsrv_close($dbhandle);
}
else {
echo "Please type a value in the search box.";
}
?>
The $query is wrong to begin with. Change it to:
$query = "SELECT * FROM Person WHERE LastName LIKE '%' + ? +
'%' AND InactiveFlag = 'N' ORDER BY LastName, FirstName";
Not sure about the tables disappearing though. What driver are you using?
Just another issue I'm seeing with the code not sure if it's related to your problem. or another copy error but here it is.
if ($r1 = sqlsrv_fetch_array($results)) {
while( $row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC)){
The first fetch should also have '($results,, SQLSRV_FETCH_ASSOC)'
Additional that check is going to eat the first returned record which may or may NOT be what you intended.
Also it is possibly that PHP seeing some results in the while as false even though they aren't and the server is still waiting on you to finish getting the rest. Seen code like that cause 'Server has got away' errors in MySQL which could be what is going on here as well.
Not sure of the syntax but a sqlsrv_clode_cursor() just before the connection close might also fix your issue if there's some kind of connection polling going on. Could be simply running out of connection or getting old one in a incorrect state.
SELECT * FROM Person WHERE AND LastName LIKE
Looks like there something missing between the WHERE and AND to me.
I don't know SQL Server really so it could allow that but it's not standard SQL. Depending on how it's reacting to that error I could see it 'Going away' so to say and reporting tables missing.

Using Session code instead of PHP SELECT WHERE function

Since my question may be unclear:
in short I am wanting to make the following code shorter and/or faster
I have login system that starts a session and runs until you logout
I also have a SELECT WHERE script that counts how many invoices have not been paid that is working just fine but is long, ugly, and bulky like so:
<?php
$con=mysqli_connect("REMOVED FOR SECURITY");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT COUNT(*) FROM mypanda_invoices
WHERE is_paid='0'");
while($row = mysqli_fetch_array($result))
{
echo "<span class='badge badge-important'>" . $row['COUNT(*)'] . "</span>";
}
?>
Right now to get the users username I have: <?php session_start(); echo $_SESSION['username']; ?> is there someway I could do this same type of thing with the code I have above? Just to make it shorter and take advantage of the session??? Thank you in advance.
As long as the session has started, you can put the invoice count in the session as well.
If you want the code cleaner, I would recommend checking for a result set and then using fetch_object()->inv_count (or, in PHP 5.4, you could use fetch_array(MYSQLI_NUM)[0] I guess).
If you have an error with a vital part of your system -- the database connection for example, you should handle it gracefully (my die below isn't graceful, but it gets the job done) instead of just echoing and continuing on, which will result in a fatal error later on.
Also, using objects will make things a bit cleaner as well.
<?php
$con = new mysqli("REMOVED FOR SECURITY");
// Check connection
if(mysqli_connect_errno()) die("Failed to connect to MySQL: " . mysqli_connect_error());
$result = $con->query("SELECT COUNT(*) AS inv_count FROM mypanda_invoices
WHERE is_paid='0'");
if($result && $result->num_rows) $_SESSION['inv_count'] = $con->fetch_object()->inv_count;
else $_SESSION['inv_count'] = 0;
echo "<span class='badge badge-important'>" . $_SESSION['inv_count'] . "</span>";

php syntax error - beginner

I'm a beginner and trying to get a handle on php. I have been getting a syntax error that I can't seem to solve. I'll show you the code below and some of the fixes I've tried. If anyone has another idea that would be wonderful. Thank you:)
$subject_set = mysql_query("SELECT * FROM subjects", $connection);
if(!$subject_set){
die("Database query failed: " . mysql_error());
}
while($subject = mysql_fetch_array($subject_set)) {
echo "<li> {$subject['menu_name']} </li>";
}
$page_set = mysql_query("SELECT * FROM pages WHERE id_subjects = {$subject["id"]}", $connection);
if(!$page_set){
die("Database query failed: " . mysql_error());
}
echo "<ul class='pages'>";
while($page = mysql_fetch_array($page_set)) {
echo "<li> {$page['menu_name']} </li>";
}
echo "</ul>";
I get: Database query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near " at line 1
I know the problem is at {$subject["id"]} because I got content back and no error when I put "WHERE id_subjects = 1". I've tried:
{$subject['id']}
{$subject[\"id\"]}
But have gotten the same error...
try
$page_set = mysql_query("SELECT * FROM pages WHERE id_subjects = '".$subject["id"]."'", $connection);
if(!$page_set){
die("Database query failed: " . mysql_error());
}
BTW. you should really move away from mysql_* functions. They are being deprecated, move to PDO or mysqli_*, which are a lot safer as well (you are now vulnerable to sql injection)
If you read back to your post, you can clearly see what's going wrong here.
"SELECT * FROM pages WHERE id_subjects = {$subject["id"]}"
As you can see "id" is not connected to the rest of the rest. That is because with the " you close the string.
To fix this simply use
"SELECT * FROM pages WHERE id_subjects = " . $subject["id"]
Or if you really want to put the variable within the string you can use a single quoted string for the key:
"SELECT * FROM pages WHERE id_subjects = {$subject['id']}"
Personally I am a fan of the first solution. But that is just my opinion.
Well when the while loop finishes looping through, it will have exhausted all the results. $subject['id'] won't have any information simply because $subject no longer has any more entries.
I'm guessing you want to list all the subjects first, then all the pages underneath each subject.
Using mySQL isn't going to be pretty but here's what you want to do. (As Bono said use PDO or mysqli, but here's a solution in psuedocode that will work with mySQL).
loop through first query
print subject name
select pages using subject id
loop through pages under that subject id
print page names
You don't need any quotes when inside a quoted string, just use
"SELECT * FROM pages WHERE id_subjects = {$subject[id]}"

Categories