I need help with this code bc im new with mysqli
i made a web to search a user and press a button to go link http://www.example.com/test.php?id=16 (16 is a example) but this code show me all the user and information of the database and i only need the information of the user with the id=16 for example.
I have done the part where i search the username and the button to send me test.php?id=16 <- id=16 is only a example bc can be any number
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>View Records</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<h1>View Records</h1>
<p><b>View All</b></p>
<?php
// connect to the database
include('connect-db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM players ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th></th><th></th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->id . "</td>";
echo "<td>" . $row->firstname . "</td>";
echo "<td>" . $row->lastname . "</td>";
echo "<td><a href='records.php?id=" . $row->id . "'>Edit</a></td>";
echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
?>
</body>
</html>
Thanks for all :)
You have to pass the condition through the query like
$id = $_GET['id'];
if ($result = $mysqli->query("SELECT * FROM players WHERE id = ".$id)) {
And please note that ORDER BY is not required here.And to prevent SQL injuctions you have to mysqli_real_escape_string the GET string.
First of all get id value in a variable.
$id_val = $_GET["id"];
And correct your sql query.
"SELECT * FROM players WHERE id ='".$id_val."'"
use where clause in the query like
if ($result = $mysqli->query("SELECT * FROM players where=".$_GET['id']." ORDER BY id"))
Related
I want to extract all records from PostgreSQL DB table and display those data using table in HTML without specifying the column name. I have many tables with many columns, so I want my query in HTML to be as responsive as it can.
Using this code below, I'm able to query the data from my database and print the data on browser, but I have to specify which column that I want to display.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8">
<title>Map</title>
</head>
<body onload="init()">
<h1>Map</h1>
<div>
<?php
$conn = pg_connect("host=localhost port=5432 dbname=visualization user=postgres password=*******");
$result = pg_query($conn,"SELECT * FROM myTable");
echo "<table>";
while($row=pg_fetch_assoc($result)){
echo "<tr>";
echo "<td align='center' width='200'>" . $row['lon'] . "</td>"; // set col manually
echo "<td align='center' width='200'>" . $row['lat'] . "</td>"; // set col manually
echo "</tr>";
}
echo "</table>";
pg_close($conn);
?>
</div>
</body>
</html>
Here's the result :
I only display 2 columns because I specified the column manually. I want to display all columns in the table with its records without specifying it manually (up to 100 columns). How to achieve that?
As your columns are in an array, you can just foreach() over the row. The display of the columns will either need to be good enough or just left as defaults to make the display look reasonable though...
while($row=pg_fetch_assoc($result)){
echo "<tr>";
foreach ( $row as $key => $value ) {
echo "<td align='center' width='200'>" . $value . "</td>";
}
echo "</tr>";
}
Try :
while($row=pg_fetch_assoc($result)){
echo "<tr>";
$maxColumnDisplay = 100;
foreach($row as $col){
if(!$maxColumnDisplay--) break;
echo "<td align='center' width='200'>" . $col . "</td>";
}
echo "</tr>";
}
Try this:
function printTable(&$result) //result set
{
/** Set up Table and Headers **/
$fieldinfo = $result->fetch_fields();
echo '<table class="sqldump">' . "\n";
echo '<tr class="header">' . "\n";
foreach ($fieldinfo as $fieldval) {
echo "<td>".$fieldval->name."</td>\n";
}
echo "</tr>\n";
/** dump rows **/
while($row = $result->fetch_assoc()) {
echo "<tr>";
foreach ($row as $column) {
echo "<td>".$column."</td>\n";
}
echo "</tr>";
}
echo "</table>\n";
/** gc **/
$result->free();
}
I am trying to use the while loop to print multiple entries from a MySQL database. Everywhere I do this it is missing the first item on the list and only manages to print from the second one on.
<?php
require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
$user = $result->fetch_assoc();
$_SESSION['file_name'] = $user['file_name'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>View</title>
<link rel="stylesheet" type="text/css" href="css/nominatorstyle.css">
</head>
<body>
<div class="header">
<h2>Results.</h2>
<form action="watch.php" method='POST'><table>
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$vid = $row['vid'];
$source = "uploads/".$row['file_name'];
echo "<tr><td>".$row['vid']."</td>
<td>".$row['file_name']."</td>";
echo "<td><a href=watch.php?
source=$source>Play</a></td></tr>";
}
}else{
echo "0 results";
}
?>
</table></form>
<button class="button-block">Home</button>
</div>
</body>
I'd like it to print all matching criteria.
I'm getting only the entries after the first one.
require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
/*
This fetch_assoc will get your first row #0 of the query
next fetch_assoc with your loop on the $result
will start as you said from row #1
*/
$user = $result->fetch_assoc(); //your missing row #0
$_SESSION['file_name'] = $user['file_name'];
You missed a "}" at the end of your while loop, that might be a problem.. I also changed your >=1 of your num_rows conditions to > 0. Try this:
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$vid = $row['vid'];
$source = "uploads/" . $row['file_name'];
$htmlRow = "<tr>\n";
$htmlRow .= "<td>" . $row['vid'] . "</td>\n";
$htmlRow .= "<td>" . $row['file_name'] . "</td>\n";
$htmlRow .= "<td>" . $row['vid'] . "</td>\n";
$htmlRow .= "<td>Play</td>\n";
$htmlRow .= "</tr>\n";
echo $htmlRow;
}
}
i'm trying to display some data from my database, and i dosen't work when i try to display some of the data, specified by a search bar. Here is the code. I hope someone can fix my problem.
Ive tried for a few hours, but nothing seems to work.
I removed most of the html code, to even be able to post.
<?php
include_once 'includes/dbh.inc.php';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<form>
<input type="text" name="search" placeholder="Search for graphicscard"/>
<input type="submit" value="Search" />
<?php
?>
</form>
<table width="600" border="1" cellpaddin="1" cellspacing="1">
<tr>
<th>Graphicscard</th>
<th>Coin</th>
<th>Hashrate</th>
<th>Bios-modded</th>
<th>Core-clock</th>
<th>Memory-clock</th>
<th>Power draw</th>
<th>Additional info</th>
</tr>
<?
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^`0-9a-z]#i","", $searchq);
$query = mysqli_query("SELECT * FROM 'cards' WHERE 'name' LIKE '$search%' OR coin LIKE '$search%'") or die ("No results");
$count = mysqli_num_rows($queryQ);
while ($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['coin'] . "</td>";
echo "<td>".$row['hashrate'] . "</td>";
echo "<td>".$row['bios_mod'] . "</td>";
echo "<td>".$row['core_clock'] . "</td>";
echo "<td>".$row['memory_clock'] . "</td>";
echo "<td>".$row['power_draw'] . "</td>";
echo "<td>".$row['additional_info'] . "</td>";
echo "</tr>";
}
}
?>
The mysqli_query() used as a function needs the link id returned by mysqli_connect() o mysqli_init()
PHP mysqli_query() Function
So you need a $connection var:
$connection=mysqli_connect("localhost","my_user","my_password","my_db");
and the use it on the query:
mysqli_query($connection, "SELECT * FROM 'cards' WHERE 'name' LIKE '$search%' OR coin LIKE '$search%'") or die ("No results");
You are using $search in the query, but the correct variable should be $searchq .
Do you get correct query result and how many rows in it? As I can see were is a mistake in your query:
SELECT * FROM 'cards' WHERE 'name' LIKE...
Name of table and fields should be in another quoats - `
SELECT * FROM cards WHERE name LIKE...
Or this is typing issue on posted message?
On this row: $count = mysqli_num_rows($queryQ); - you variable of query result is - $query not $queryQ
Here is an alternative way:
select * from cards where name like 'ABC%'
union
select * from cards where coin like 'XYZ%'
union
select * from cards where gender like 'PQR%';
Change your code on this:
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^`0-9a-z]#i","", $searchq);
$query = mysql_query("SELECT * FROM cards WHERE name LIKE '$searchq%' OR coin LIKE '$searchq%'") or die ("No results");
$count = mysql_num_rows($query);
while ($row = mysql_fetch_array($query)) {
echo "<tr>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['coin'] . "</td>";
echo "<td>".$row['hashrate'] . "</td>";
echo "<td>".$row['bios_mod'] . "</td>";
echo "<td>".$row['core_clock'] . "</td>";
echo "<td>".$row['memory_clock'] . "</td>";
echo "<td>".$row['power_draw'] . "</td>";
echo "<td>".$row['additional_info'] . "</td>";
echo "</tr>";
}
}
If you use mysqli please see this referenc on how to use it
in your tag form add method of sending data POST: <form method="POST">
i will use my old posted codes, coz i am working on the same program. what i want is how could i make it possible to save all selected values in one row which the studentid of a user will not be repeated. pls help...
<?php session_start(); ?>
<?php
//server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'user';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
?>
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
echo 'Student ID: '. $voter.'';
echo "<br />";
if ($_POST['representatives']){
$check = $_POST['representatives'];
foreach ($check as $ch){
global $voter;
$mysqli->query("INSERT INTO sample (studentid, candidate1) VALUES ('".$voter."', '". $ch ."')");
echo $ch. "<br>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<script type="text/javascript">
<!--
function get_representatives_value()
{
for (var i=0; i < document.list.representatives.length; i++)
{
if (document.list.representatives[i].checked)
{
return document.getElementById('candidates').innerHTML = document.list.representatives[i].value
}
}
}
//-->
</script>
title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="candidate.css" rel="stylesheet" type="text/css">
</head>
<body> <p id="txt"></p>
<form name="list" action="president2.php" method="post" onSubmit="return get_representatives_value()">
<div id="form">
<?php
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM candidate_info WHERE position= 'representatives' AND department ='CCEITE' ORDER BY cand_id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table border='1' cellpadding='10'>";
// set table headers
echo "<tr><th>Student ID</th><th>Candidate ID</td><th>Course</th><th colspan = '3'>Name</th></tr>";
while ($row = $result->fetch_object())
{
// set up a row for each record
echo "<tr>";
echo "<td>" . $row->cand_studid . "</td>";
echo "<td>".$row->cand_id."</td>";
echo "<td>" . $row->course . "</td>";
echo "<td coslpan ='5'>" . $row->fname . " ". $row->mname ." ". $row->lname ." </td>";
echo "<td><input type ='checkbox' name='representatives[]' id='". $row->cand_studid ."' value='" . $row->cand_studid . "' onchange='get_representatives_value()' /></td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
echo "<input type='submit' name='representatives value='Submit' />";
?>
</div>
</form>
<table>
<tr><td>Preview List</td></tr>
<tr><td>Candidates: </td><td id="candidates"> </td></tr>
</table>
</body>
</html>
this the preview of my output and selected checkbox
now this is the preview of my database. this one is the result of my selection from the above preview which the student ID is repeated on my table.
what i want is to save like this
and one more thing, how could i make a preview of all i selected on the checkboxes, here is my preview output, below the table is the preview list of candidates as the user click on the checkbox. but it returns only one and only the last selected value as selecting multiple checkboxes will be printed. how could i apply this method in an array coz this preview, i remove the '[]' on my input type name='representative' and it works, but not in the presence of '[]'.
I don't know if I read your questions correctly, but...
For your Insert Issue
I don't know if the way you're storing the data in the database is the best method, but if you want to use what you have, you can just insert your record like this (assuming you've put in some validation script to prevent users from selecting more than 2 candidates):
<?php
$_SESSION['username'];
$voter = $_SESSION['username'];
if ($_POST['representatives']){
$check = $_POST['representatives'];
$mysqli->query("INSERT INTO sample (studentid, candidate1, candidate2) VALUES ('". $voter ."', '". $check[0] ."', '". $check[1] ."')");
}
}
?>
For your Preivew Issue:
I'm assuming you wanted something like this for your preview to show the studentid with the choices for candidate1 and candidate2:
<h3>Preview List</h3>
<table>
<tr><th>StudentID</th><th>Candidate 1</th><th>Candidate 2</th></tr>
<?php
$result = $mysqli->query("SELECT * FROM candidate_info");
while ($row = $result->fetch_object())
{
echo "<tr><td>" . $row->studentid . "</td><td>" . $row->candidate1 . "</td><td>" . $row->candidate2 . "</td></tr>";
}
$mysqli->close();
?>
</table>
Here is some pseudo code you can use to update the sample table:
$candidate=array(null,null);
$candidateCounter=0;
foreach ($check as $ch){
$candidate[$candidateCounter]=$ch;
$candidateCounter++;
if(candidateCounter>1){
something wrong, only 2 candidates can be selected
}
}
UPDATE sample set $candidate1=candidate[0], $candidate2=candidate[1] WHERE
studentid=$voter
EDIT
I have a mysql table with fields as follows:
Products - serial, name, description, price, picture.
the viewproducts.php page is as follows:
<?php
$result = mysql_query("SELECT * FROM products ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
echo '<td> Edit</td>';
}
}
echo "</tr>";
echo "</table>";
?>
my edit.php page looks like this:
<?php
$product_id = $_GET['serial'];
$result = mysql_query("SELECT * FROM products WHERE serial = '$product_id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'There Arent Any Products';
} else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $info['name']. "</td>";
echo "<td>" . $info['description']. "</td>";
echo "<td>£" . $info['price']." </td>";
echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
}
}
echo "</tr>";
echo "</table>";
?>
when i click on edit from thr viewproducts.php page, it goes to edit.php page where nothing is showing up. the serial id on the address bar is coming up as follows:
http://www.********.com/****/admin/edit.php?product_id=
I want to be able to edit any product clicked on from the viewproduct.php page and transfered to edit.php page. I dont think my edit.php page is set up corretly.
Please help,
Thanks
You can pass via $_GET the id of the product and then, in the edit/delete page, retrieve that parameter. Obviously you have to sanitize the input properly before using it. For example, the link of the each product should look like this:
echo '<td>Edit</td>';
In the edit page you should have something like:
$id = $_GET['id'];
// For example, if the product id is an integer
// you can sanitize it doing this
$id = (int) $id
You could pass it as an argument to your php file in wich you want to edit/delete the product:
Edit Product
Then in your edit.php you will pick up the id of the product and load it's data from the database.
[edit.php]
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : null;
if(!$product_id) {
exit();
}
// query your database for the product
$row = mysqli_query("SELECT * FROM <table> WHERE product_id = $product_id");
// then you output your html with fields populated from the result from the database