PHP code not executing - php

$sql1=mysql_query("SELECT * FROM Persons", $con);
echo "<table border="3">
<tr>
<th>Name</th>
<th>Age</th>
</tr>";
while($info=mysql_fetch_array($sql1))
{
echo "<tr>";
echo "<td>" . $info['fname'] . "</td>";
echo "<td>" . $info['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
this code is a part of a code which is trying to retrieve data from the table"Persons",
there is some error in this part of the code..

You have double quotes in the quoted html. Try using single quotes in stead, i.e.
echo "<table border='3'> <--- here
<tr>
<th>Name</th>
<th>Age</th>
</tr>";

Your code looks ok, except for the unescaped double quotes:
It should be:
echo "<table border=\"3\"> ... ";
or
echo '<table border="3"> ... ';
Make sure it is enclosed in <?php and ?>.
Also make sure your db columns names of fname and age really exist....
Make sure you're getting what you think back from the DB, by using print_r($info) or var_dump($info).
Finally, your connection $con could be broken / not working. You can check that by using:
if ( ! $con ) {
die('Could not connect: ' . mysql_error());
}
$sql1 = mysql_query("SELECT * FROM Persons", $con);
...

Beside double quotes in second line.
mysql_fetch_array return array indexed by integer if you want asoc array indexed by fields use mysql_fetch_assoc
while ($info=mysql_fetch_assoc($sql1)) {
...
}

Related

SIMPLEST update to MYSQL from PHP

I am passing over a factory operations system to a new support team and I am writing a guide for that.
It has a VERY simple DB section tucked inside and I just want very basic set of procedures for demonstration to the team who are very IT literate but do not have any DB or PHP experience.
I have finished most of the guide but having a bit of a problem with a simple Quantity update procedure.
Be clear - I have no problem doing it but I have searched and searched for a simple answer and also everything I do seems just far more complex than it needs be. Can anyone assist with simplicity !
As the base exampler I am using the well tried
<?php
$con=mysqli_connect('localhost', 'bbbbbb', 'bbbbb', 'bbbbbbl') or die(mysql_error());
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM orders_products");
echo "<table border='1'>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Quantity</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['products_id'] . "</td>";
echo "<td>" . $row['products_name'] . "</td>";
echo "<td>" . $row['products_quantity'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
which gives a simple table at the level I need
NOW all I want to demonstrate is how to update some or all of the Product Quantities in the list back to the MYSQL database. BUT AS SIMPLY AS POSSIBLE Without using individual "Edits" for each row. Apologies if this is too low level for you chaps !
NOTE: Edited to improve secrurity, but this does NOT negate the need for prepared statements to prevent other SQL injection attacks.
Wrap
<form method='POST' action='?'> around the table.
Replace
echo "<td>" . $row['products_quantity'] . "</td>";
With
$iProctId = $row['products_id'];
$iQuantity = $row['products_quantity'];
echo "<td>";
echo "<input type='text' name='product[{$iProductId}]' value='{$iQuantity}'/>";
echo "</td>";
In your script:
foreach( $_POST['product'] as $iProductId => $iQuantity ) {
mysqli_query( $con,"
UPDATE
orders_products
SET
products_quantity = ".(int)$iQuantity."
WHERE
products_id = ".(int)$iProductId."
");
}
Disclaimer
This script is simple, but not safe! To get it safe: mysqli_real_escape_string and mysqli_prepare
Enjoy :)

Why is data is not printed on webpage, after being fetched from mysql database?

$retval = mysqli_query($conn,"SELECT * FROM food WHERE pnrno='$pnrno'");
if ($retval) {
echo "Your food complain has been successfully fetched";
echo "<table border='1'>
<tr>
<th>Username</th>
<th>PNR Number</th>
<th>Food Complain Status</th>
</tr>";
while($row = mysqli_fetch_array($retval))
{
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['pnrno'] . "</td>";
echo "<td>" . $row['complain_status'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "\r\n";
} else {
echo "Error: " . $retval . "<br>" . mysqli_error($conn);
}
Code inside the while loop is not getting executed(I think so), "Your food complain has been successfully fetched" this message is getting printed, table is formed, but username, pnrno, and complain_status after being fetched from database is not printed on webpage. Why is it so, please help.
Assuming the data exists, and you're sending the query the correct parameter, the likely culprit is how you're using your row variable. Since you're not telling mysqli to fetch the array in an associative manner, it's defaulting to an index.
You need to change your fetch function to:
mysqli_fetch_array($retval, MYSQLI_ASSOC)
$retval = mysqli_query($conn,"SELECT * FROM food WHERE pnrno='$pnrno'");
if ($retval) {
Your if is going to execute if the query successfully executes.
However, a query for a non-existent row will succeed, with zero rows.
You'll want to check the number of rows returned by the query, and show an error if there aren't any matching ones.

Using PHP variable in mysql_query string

OK guys. I have a somewhat complicated issue with passing PHP variables into the mysql_query string.
The $_GET['date']; when passed will contain something like: 2015_01_07_1
I need to have the GET data passed into the table names using the $week variables.
<?php
$week= $_GET['date'];
$con=mysqli_connect("localhost","root","mypassword","beerhandpoker");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query
($con,
"SELECT games_brixx_gastonia_'$week'.rank, players_brixx_gastonia.name, games_brixx_gastonia_'$week'.points
FROM games_brixx_gastonia_'$week', players_brixx_gastonia
WHERE games_brixx_gastonia_'$week'.email = players.email
ORDER BY games_brixx_gastonia_'$week'.rank
LIMIT 20"
);
echo "<table>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['rank'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['points'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Change the string literal to:
"SELECT games_brixx_gastonia_$week.rank,
players_brixx_gastonia.name,games_brixx_gastonia_$week.points
FROM games_brixx_gastonia_$week, players_brixx_gastonia
WHERE games_brixx_gastonia_$week.email = players_brixx_gastonia.email
ORDER BY games_brixx_gastonia_$week.rank
LIMIT 20"
You have to remove the ' characters;
It's going to the db as games_brixx_gastonia_'2015_01_07_1'.rank
Why do you put single quotes? It should work:
SELECT games_brixx_gastonia_{$week}.rank, players_brixx_gastonia.name, games_brixx_gastonia_{$week}.points
FROM games_brixx_gastonia_{$week}, players_brixx_gastonia
WHERE games_brixx_gastonia_{$week}.email = players.email
ORDER BY games_brixx_gastonia_{$week}.rank
LIMIT 20
Anyway, I'd rather advice you to use statement instead. Check it out:
http://php.net/manual/pt_BR/mysqli.prepare.php
Just remove the ' characters. Otherwise the query would try to get data from the table games_brixx_gastonia_'2015_01_07_1' and not games_brixx_gastonia_2015_01_07_1.

Trying to pass a student key from a html form to a php file to scan a database

Basicaly having issues setting up a webpage which will taken in a student key entered by the user. This will then parse the student key to another file which will run it against a mysql backend to see what records this student already has. But can not get it working for the life of me please help I'm still a newb at this.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("support_log", $con);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like '$_POST[stkey]'");
$result2 = mysql_query($result) or die("Error: " . mysql_error());
if(mysql_num_rows($result2) == 0){
echo("no records found");
} ELSE {
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Surname</th>
<th>Year Group</th>
<th>Student Key</th>
<th>Issue</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['year_group'] . "</td>";
echo "<td>" . $row['stkey'] . "</td>";
echo "<td>" . $row['issue'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($con);
?>
After changing my where statement to:
WHERE student.STKEY like '$_POST[stkey]'");
I am no longer reciving errors from PHP but now recieving the error Query was empty which is part of my code to detect if there is no results. Though I have tested that query in phpmyadmin and it spits out results. From looking at the code does anyone have any solutions? I have also checked the parse by running an echo on the post command to ensure the data being entered was correct.
Edit: Got rid of the whole result2 check now throwing a:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\stkey_submit.php on line 24
Try $_POST['stkey'] instead of $_POST[stkey]
EDIT : if you use it in a query, it would be preferable to do :
$stkey = mysql_real_escape_string($_POST['stkey']);
$sql = "SELECT ....... like '$stkey'";
mysql_query($sql);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like " . $_POST["stkey"]);
How about storing the value of stkey on a variable before including it on the query?
$stkey = $_POST['stkey'];
$result= mysql_query("SELECT student.first_name, student.surname,
student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY LIKE '%$stkey%'");
You might also want to use MySqli or PDO instead of the MySql database API. Take a look at this post from Nettuts: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/

Display SQL Table in PHP

I am trying to display a table in php. I have established a valid connection. I get the error:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /Applications/XAMPP/xamppfiles/htdocs/project.php on line 17
The page's code:
<html>
<head>
<title>PHP Site Michael Mazur</title>
</head>
<body>
<?php
//connect to DB
$con=mysql_connect("localhost","mike","mike");
$db_found = mysql_select_db("my_guitar_shop2");
$result = mysql_query("SELECT firstName,lastName FROM customers");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['firstName'] . "</td>";
echo "<td>" . $row['lastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
The rest of your while loop could look like this
while($row = mysql_fetch_array($result)){
print "<tr><td>".$row['Firstname']."</td><td>".$row['Lastname']."</td></tr>";
}
print "</table>";
Try putting these lines on a single line as i have done above.
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
like
echo "<table border='1'><tr><th>Firstname</th><th>Lastname</th></tr>";
Other useful options here.
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/control-structures.foreach.php
Given that part of the page's code is missing, this is only a guess. But it looks like part of your problem is that you've double-selected the database (a no-no).
Also, the while statement looks slightly suspect (no opening brace to verify context).
Additionally, if you are going to pass $con to the database selector, you should also pass it to the mysql_query calls (good practice for readability).

Categories