Need to display a MySQL table on a page using PHP - php

I'm trying to get a table to display and keep getting an error. Could someone out there with better coding skills help me?
Here is the code:
<?php
// connect to the database
$host = "###";
$username = '###';
$pass = '###';
mysql_connect($host,$username,$pass) or die(mysql_error());
mysql_select_db("Employees") or die(mysql_error());
// select everything from the table
$query = "SELECT * FROM Employees";
$result = mysql_query($query') or die(mysql_error());
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>
When the page runs it yields the following error:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /home/content/35/4683335/html/crosshill/display.php on line 36
Line 34 is: echo "<td>".$row['employeeid']."</td>";

I suggest that you need check 3 points:
You could use or die(mysql_error()) in dev environment to check if you have an error (with sql functions related).
Connection
mysql_connect($host,$username,$pass) or die(mysql_error());
Select db
mysql_select_db("Employees") or die(mysql_error());
Query (I see that you query are correct, but probably you table name are wrong, remember that names are case sensitive)
$result = mysql_query($query) or die(mysql_error());

I noticed your database is called Employees as well as your table, is this a mistake or are they both the same name?
You also have syntax error here:
$query = "SELECT * FROM Employees";
$result = mysql_query($query') or die(mysql_error());
Remove the ' so it is like this:
$result = mysql_query($query) or die(mysql_error());
Try this:
$query = "SELECT * FROM Employees";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result)< 1){
echo 'no rows founds';
} else {
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_assoc($result)))
{
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
}
echo "</tr>";
echo "</table>";
}
Side note:
As suggested by others you should switch to either mysqli_* or perhaps pdo.

Related

Call to a member function query() on a non-object on line

I can't seem to figure out what is going on here... or why this isn't working. The code works on a different database... so I'm not sure what is going on?
<?php
//connect to the database
$con = new mysqli("localhost", "rreedy", "quixtar1");
$con->select_db("attendance");
//display success or failure
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . $con->connect_errno;
}
echo "<label for='evtCode'>Event</label><br/>";
echo "<select id='evtCode' class='form-control' name='evtCode'>";
echo "<option value=1>Text</option>";
$query = "SELECT * from tbldata";
$result = $con->query($query);
while($row = mysqli_fetch_array($result))
echo $row['courseName'];
echo "</select>";
?>
You have a typo, it should be:
$result = $con->query($query);
Your mysqli object is in $conn. You're also mixing procedural and object oriented together.
echo "<option value=1>Text</option>";
$query = "SELECT * from tbldata";
$result = $con->query($query);
while($row = $result->fetch_array(MYSQLI_ASSOC))
echo $row['courseName'];
echo "</select>";
What I changed
$con->query()
$row = $result->fetch_array(MYSQLI_ASSOC)
The docs
query
fetch_array

Struggling with php SELECT

I have used the below code in my website,
<?php
$con= mysqli_connect("*******","******","*****", "catalejo_articles");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= mysqli_query($con, "SELECT * FROM baul");
while($row = mysqli_fetch_array($result))
{
echo $row['title'] . " " . $row['date'];
}
mysqli_close($con);
?>
and it is not working. What am i doing wrong??
I am new to php and mysql, any help will be appreciated.
UPDATE:
I want to thank and apologize to all of you who spent precious time trying to help me. I just solved the problem, the original code was OK. The problem was I didn't change the file extension to PHP.
Make sure display error is enabled. add this line at the top of your page and see if it display any error :
error_reporting(-1);
And try inside while loop :
var_dump($row)
Does table contains data?
Try this way,
if ($result = mysqli_query($con, "SELECT * FROM baul", MYSQLI_USE_RESULT)) {
while($row = mysqli_fetch_array($result))
{
echo $row['title'] . " " . $row['date'];
}
mysqli_free_result($result);
}
Check if u have any records in your table using mysqli_num_rows
$con= mysqli_connect("*******","******","*****", "catalejo_articles");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= mysqli_query($con, "SELECT * FROM baul");
$count = mysqli_num_rows($result);
if($count > 0)
{
while($row = mysqli_fetch_array($result))
{
echo $row['title'] . " " . $row['date'];
}
}else{
echo "No Records found in the table";
}
mysqli_close($con);
From what I can make out of your code, since you were attempting to reference by association instead of by numerical index, you weren't seeing anything because you were missing MYSQLI_ASSOC in your while loop:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['title']." ".$row['date'];
}
Otherwise you need to know where "title" and "date" columns are located and reference them by numerical value:
while($row = mysqli_fetch_array($result)) {
echo $row[0]." ".$row[1];
}
Alternatively, if mysqli_fetch_array is not working (due to PHP version), try using:
while($row = mysqli_fetch_assoc($result)) {
echo $row['title'].' '.$row['date'];
}

Passing value from a hyperlink to new page

Can someone take a look at my code? I am trying to display a record from a link from the previous page. When I echo $id (below)... it displays the value of 'id' from the previous page. However the query returns all rows of the table. I had it working earlier. I have since changed something. Pleas point out what I over looking. Thank you, in advance.
<?php
mysql_connect('host', 'userid', 'password') or die (mysql_error());
mysql_select_db('my_database') or die (mysql_error());
//$result = mysql_query("SELECT * from table");
$id= mysql_real_escape_string($_GET["id"]);
echo $id;
$result = mysql_query("SELECT * FROM uatbeta1 WHERE id=".intval($_REQUEST['id']));
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $result;
while($row = mysql_fetch_array($result)){
//Display the results from the current row and a line break
echo "<table border='1'>";
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['company']."</td>";
echo "<td>".$row['constructioncontractor']."</td>";
echo "<td>".$row['weldingcontractor']."</td>";
echo "<td>".$row['ndtcontractor']."</td>";
echo "<td>".$row['weldid']."</td>";
echo "<td>".$row['projectname']."</td>";
echo "<td>".$row['examinationdate']."</td>";
echo "<td>".$row['shift']."</td>";
echo "</tr>";
Why not use $id? You have it nicely escaped, so use that variable:
$result = mysql_query("SELECT * FROM uatbeta1 WHERE id=".$id);

MySQL insert row from HTML table into db table

I am using a for loop to construct a HTML table from the contents of a MySQL table select query. I have a link on the end of each row to copy that row into another table.
I'm unsure how to get the data from the table row for the MySQL insert query - I have marked the place where I'm struggling with XXX.
<?php
mysql_select_db("cardatabase");
$link = mysql_connect("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query($query);
if($_GET['rent']) {
$rent = "INSERT INTO rentedcars VALUES('XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr><td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td></tr>";
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_object($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
edit (updated code):
<?php
mysql_select_db ("cardatabase");
$link = mysql_connect ("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query ($query);
if($_GET['rent']) {
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']);
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt);
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr>";
echo "<td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td>";
echo "</tr>";
while ($row = mysql_fetch_object($result)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
mysql_* is deprecated as of PHP 5.5.0, you should use something like PDO.
try {
$DBH = new PDO('mysql:dbname=cardatabase;host=localhost', 'root', 'password');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$STH = $DBH->query("SELECT * FROM cars")->execute();
while ($row = $STH->fetch(PDO::FETCH_OBJ)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=".$row->ID."'>Rent</a></td>
</tr>";
}
Edit: Just like #Skatox said!
I would do it like this:
<?php
$link = mysql_connect ("localhost", "root", "password");
mysql_select_db ("cardatabase");
$query = "SELECT * from cars";
$result = mysql_query ($query);
Get car information and store it
if($_GET['rent'])
{
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']); //Avoids sql injection
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt)
Here you need to validate if there's no car
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
Change it to while like #Vinoth Babu said:
while ($row = mysql_fetch_object ($result))
{
$row = mysql_fetch_object ($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
print "</table>";
?>
I would recommend you to switch to MySQL PDO, it's safer and you'll get a better and secure code.
you are missing the column names in your insert query
$rent = "INSERT INTO rentedcars (id ,carmake, carmodel,fueltype,transmission, enginesize,doors,amount ,available, dateadded)
VALUES('xxx','xxx','".$carmodel."','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
^^^^^-------------i showed u exempel under
those XXX are values you get the from the inputs values
exemple
<input name= "car_model" id= "car_model" value="mercedes" >
then you get this value
if (isset($_POST['car_model'])){ $carmodel = $_POST['car_model']}
and then use this value $carmodel in your sql

Listing the tables content in the database

written a script to print the contents of all the tables present in the database...
but unfortunately i am going wrong somewhere. could anyone please tell me where is the mistake?
$sql = "SHOW TABLES FROM $dbName";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
for ($i=1; $i<=5; $i++)
{
while ($row = mysql_fetch_row($result))
{
echo "Table: {$row[0]}\n";
$sql_1 = "SELECT * FROM {$row[0]}";
$result_1 = mysql_query($sql_1);
$row_1 = mysql_fetch_row($result);
echo "$row_1";
}
}
mysql_free_result($result);
?>
thanks..
first of all, u don't need
for ($i=1; $i<=5; $i++)
Also, $row_1 is an array, so to print it use something like
print_r($row_1);
And there might be not the only row in a table, so use construction like
while ($row = mysql_fetch_row($result))
{
echo "Table: {$row[0]}\n";
$sql_1 = "SELECT * FROM {$row[0]}";
$result_1 = mysql_query($sql_1);
while ($row_1 = mysql_fetch_row($result_1/*There was also an error*/))
print_r($row_1); /*Print_r or other function to print an array*/
}

Categories