Retrieve 1 value that links to all values from database - php

So I'm trying to display a list of all users in my database... each one with a link that will display their own information (in this case only displays user again and password), heres my code...
<?php
mysql_connect('localhost','user','password')or die ('Connection Failed: '.mysql_error());
mysql_select_db('name')or die ('Error to select database '.mysql_error());
$result = mysql_query("SELECT * FROM usuarios ORDER BY ID");
echo "<table border='0'>
<tr>
<th>UserName</th>
</tr>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo '<td>' . $row['usuario'] . '</td>';
echo "</tr>";
}
echo "</table>";
?>
I get the ID of each user through the URL to be a new variable in my user.php page to recognize each one...
<?php
$numusu = $_GET['id'];
$result = mysql_query("SELECT * FROM usuarios WHERE id=`$numusu`");
while ($row = mysql_fetch_array($result))
{
echo "<table><tr>";
echo "<td>User:" . $row['usuario'] . "</td>";
echo "<td>Password:" . $row['password'] . "</td>";
echo "</tr></table>";
}
?>
But for some reason I'm not able to display anything in user.php, I get the ID value and all just missing the information I just get an error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource in /site/test/test/test/login_php/user.php on line 15
What am I doing wrong? Please help me!

The query should be SELECT * FROM usuarios WHERE id='$numusu'. Backticks only work for table and database names.
When you get Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource, it usually means $result is null and/or mysql_query failed. If you change the query to
$result = mysql_query("...") or die(mysql_error());
It should tell you that something like Unknown column '1' in 'where clause'.

Related

Print a row from a database

I need to print a row from a database, i know how to print columns, but having a hard time printing rows. Can someone tell me how to?
<?php
$query = "SELECT * FROM categorias ";
$result = mysqli_query($conn, $query) or die (mysql_error());
while ($categoria = mysqli_fetch_array($result)) {
echo "<p>" . $categoria ['descricao'] . "</p>";
}
?>
This is how im printing columns
The answer is don't use SELECT * in PHP, it's extremely prone to errors. If you explicitly list the columns in your select statement you can concatenate them into a table in PHP.
Hope this helps.
Use print_r to debug selected data.
Also look for Mysql Fetch Row
Always Use Google
<?php
$query = "SELECT * FROM categorias ";
$result = mysqli_query($conn, $query) or die (mysql_error());
if(mysqli_num_rows($result)>0)
{
while ($categoria = mysqli_fetch_array($result)) {
echo "<p>" . $categoria['descricao'] . "</p>";
}
}
?>
<table><tr><?php
while ($categoria = mysqli_fetch_array($result)) {
echo "<td>" . $categoria ['descricao'] . "</td>";} ?></tr></table>
I use a table, where while the array is true places the values cell by cell in a row, because the loop is working inside the <tr> </tr> creating a new <td> for every record.

PHP ID not going through url

i cannot get a row to delete as the id is not going through the url. its a simple error somewhere and i cannot find the solution after having a look around for an hour.
this page contains the information on a table:
<?php
$result = mysql_query("SELECT review, ratings, date, user FROM reviews")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Reviews Yet';
} else {
echo "<table border='0'><table width=100% border='6'><tr><th>Comments/Thoughts</th><th>Ratings</th><th>Date</th><th>User</th><th>Delete</th></tr>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['review']. "</td>";
echo "<td>" . $info['ratings']. " Stars</td>";
echo "<td>" . $info['date']. "</td>";
echo "<td>" . $info['user']. "</td>";
echo "<td>" . " <a href='deletereview.php?review_id=" . $info['review_id'] . "'>Delete</a> </td>";
echo "</tr>";
}
}
echo "</table>";
?>
it goes to deletereview.php which carries out the delete function:
<?php
session_start();
require_once '../includes/db.php';
$id = $_GET['review_id'];
$info = "DELETE FROM reviews WHERE review_id = '$id'";
mysql_query($info) or die ("Error: ".mysql_error());
echo "<h2>Review Deleted</h2>";
?>
any ideas guys?
You're not selecting the review_id in the query, so $info["review_id"] is always null.
Aside from the other answers, I'll say this:
Your database will get jacked if you do not sanitize your variables.
For instance, what happens if I pass review_id=' OR '1'='1?
DELETE FROM reviews WHERE review_id = '' OR '1'='1'
This query will delete everything in reviews.
mysql_real_escape_string() your $_GET and $_POST variables before using them in your MySQL.
You forgot to select the review_id.
$result = mysql_query("SELECT review_id, review, ratings, date, user FROM reviews")
You're not selecting review_id from the database but you use $info['review_id'] to set the ID on the URL. Just change your first line to:
$result = mysql_query("SELECT review_id, review, ratings, date, user FROM reviews")
Also you must escape the input with mysql_real_escape_string:
$id = mysql_real_escape_string($_GET['review_id']);
You have to select the review_id in the query. But also you have to check for some SQL injection, because with the GET request it's easy to delete all the table records.

mysql_num_rows() not a valid resource - mysql_error() shows nothing

I have the following code.
include("DBHeader.inc.php");
include("libs/ps_pagination.php");
$sql = "SELECT * FROM Products P, Manufacturers M WHERE M.sManufacturerCode='$LC' AND M.iManufacturerID=P.iManufacturerID";
$rs = mysql_query($sql);
echo $sql;
$pager = new PS_Pagination( $conn, $sql, 3, 4, null );
$rs = $pager->paginate();
$num = mysql_num_rows( $rs ) or die('Database Error: ' . mysql_error());
if ($num >= 1 ) {
echo "<table border='0' id='tbProd' class='tablesorter' style='width:520px;'>
<thead>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th> </th>
</tr>
</thead>
<tbody>";
//Looping through the retrieved records
while($row = mysql_fetch_array($rs))
{
echo "<tr class='prodRow'>";
echo "<td>" . $row['sProductCode'] . "</td>";
echo "<td>" . $row['sProductName'] . "</td>";
echo "<td><a href='ProdEdit.php?=" . $row['sProductCode'] . "'><img src='images/manage.gif' alt='Edit " . $row['sProductName'] . "' /></a></td>";
echo "</tr>";
}
echo "</tbody></table>";
}
else {
//if no records found
echo "No records found!";
}
And instead of it giving me the data from the table, it spits out on the screen:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/nyksys/www/regserver2/search_results.php on line 37
mysql_error() is actually returning nothing at all, so I'm very confused as to what the error is. The SQL when echo'd:
SELECT * FROM Products P, Manufacturers M WHERE M.sManufacturerCode='216E3ACAC673DE0260083B5FF809B102B3EC' AND M.iManufacturerID=P.iManufacturerID
I'm baffled here! Am I overlooking something simple here?
I've double checked my database information, I'm certain that isn't the problem.
EDIT- I'm following the tutorial Paginating Your Data with AJAX and Awesome PHP Pagination Class.
$sql = "SELECT * FROM Products P, Manufacturers M WHERE M.sManufacturerCode='$LC' AND M.iManufacturerID=P.iManufacturerID";
$rs = mysql_query($sql);
echo $sql;
$rs is a MySQL result resource that you could use with mysql_num_rows.
$pager = new PS_Pagination( $conn, $sql, 3, 4, null );
$rs = $pager->paginate();
Now it's not1!
$num = mysql_num_rows( $rs ) or die('Database Error: ' . mysql_error());
Oops!
1 Or, if it is, [a] you didn't show us that in your question, and [b] the original query was entirely pointless.
You are overwriting the $rs variable
My guess is whatever the PS_Pagination class is doing, it is not returning a MySQL resource. You are overwriting your $rs resource variable with that object, and it ceases to be a valid resource, even if your query succeeds.
$rs = mysql_query($sql);
echo $sql;
$pager = new PS_Pagination( $conn, $sql, 3, 4, null );
// Use a different variable than $rs here.
$rs = $pager->paginate();

Unknown column 'mush' in 'where clause'

I was testing a simple employee application and got this Unknown column 'mush' in 'where clause' error. There is someone called 'mush' in the name's column.
Here's my code
<?php
// Connects to your Database
mysql_connect("localhost", "myuser", "mypass") or die(mysql_error()) ;
mysql_select_db("peoplesdb") or die(mysql_error()) ;
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM employees WHERE name = $_GET[name]") or die(mysql_error());
echo "<table border=\"1\">";
echo "<tr>";
echo "<th>First Name:</th>";
echo " <td>Last Name</td>";
echo "</tr>";
echo "<tr>";
echo "<th rowspan=\"3\"><img src=\"../about/images/".$data['photo']."\" width=\"205\" height=\"205\" alt=\"\" title=\"\"></th>";
echo $data['name'];
echo "<td>".$data['name'] ."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>".$data['lastname'] ."</td>";
echo "</tr>";
echo "</table>";
?>
The aim was to display the detail on a table with a picture to the left of the table.
Here's how I tried calling the application:
http://localhost:8080/displaymembers.php?name=mush.
I have a table which contains these columns:
name, photo, telephone, lastname and dob.
Is there anything I'm going wrong that stops the details from displaying? I would like your help.
Helen.
First, you need to quote your inputs, second you need to escape them:
mysql_query("SELECT * FROM employees WHERE name = '".
mysql_real_escape_string( $_GET['name'] ) ."'");
You need to enclose it in quotes - e.g.
SELECT * FROM employees WHERE name = '{$_GET[name]}'
I would also suggest you use mysql_real_escape_string:
$data = mysql_query("SELECT * FROM employees WHERE name = '" . mysql_real_escape_string($_GET['name']) . "';") or die(mysql_error());
Try those put single quotes around your variable.
$_GET['name'];
And use mysql_real_escape_string to avoid SQL Injections.
you should try
$data = mysql_query("SELECT * FROM `employees` WHERE `name` = '".mysql_real_escape_string($_GET['name'])."'") or die(mysql_error());
as name may be reserved for mysql purposes, and I believe it is ...

Not able to delete the database(mySQL) record in PHP, where did i go wrong?

I am trying to delete the records from the users table in mysql,
the code goes like this.
if(isset($_GET['id'])) {
//create query to delete the record
$query = "DELETE FROM users WHERE id =" . int($_GET['id']) or die(mysql_error());
//execute query
if($mysqli->query($query)) {
//print number of affected rows
echo $mysqli->affected_rows. " row(s) affected";
}
else {
//print error message
echo "Error in query : $query " . $mysqli->error;
}
}
else {
echo "Could not Execute the Delete query";
}
at the same time i am iterating the records from the users table in the database and it goes like this.
//query to get records
$query = "SELECT * FROM users";
//execute query
if($result = $mysqli->query($query)) {
// see if any rows were returned
if($result->num_rows > 0) {
// if yes then print one after another
echo "<table cellpadding=10 border=1>";
while($row = $result->fetch_array()) {
echo "<tr>";
echo "<td>" .$row[0] . "</td>";
echo "<td>" .$row[1] . "</td>";
echo "<td>" .$row[2] . "</td>";
echo "<td>Delete</td>";
echo "</tr>";
}
echo "</table>";
}
$result->close();
}
the problem is, i am able to get the records from the database and display it in the browser but when i try to delete the record the first condition does not pass i.e if(isset($_GET['id'])) instead it goes to else condition and print the message "Could not Execute the Delete query " , i guess it is not able to fetch the $_GET['id'] so only it refuses to enter the if condition,
P.S :i would appreciate if someone explains me in simple words, i am a newbie to programming, thanks..
You are missing an =:
echo "<td>Delete</td>";
HERE -------------------^
"DELETE FROM users WHERE id =" . int($_GET['id']) or die(mysql_error());
Shouldn't it be intval instead? There's no function int in PHP. There's also (less preferably) the cast to int, like this: (int) $_GET['id']).

Categories