Getting User Data Based on Their Information - php

This first field is where a web visitor will enter in the 'cardname' hit submit and be directed to another page (dashboard2.php) where only his or her content will appear.
Enter your cardname to access your content<br>
<form action='dashboard2.php'>
<input type='text' name='cardname'/><input type='submit' value='retrieve card'/>
</form>
</body>
The page below is the page that is directed after the user enters in the 'cardname' from the first input field. However, I only want this second page to show the information based on the cardname that was entered. Right now, it shows every single cardname, questionone, answerone from that table.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

You have to modify the query to accept a WHERE clause. For instance, WHERE cardname = mysqli_real_escape_string($conn, $_GET['cardname']) (The default method for any form is GET unless you specify method="post".).
You should learn about prepared statements for MySQLi and perhaps consider using PDO, it's really not hard.

It seems that you want to perform a search and not a display all the records.
Usually a search returns records that match a certain field, unless a specific ID or unique value was entered in the search. I'm not sure this is the case.
I put this together a little quick but hopefully it helps...
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// escape the string to avoid SQL injections
$searchEscaped = $conn->real_escape_string($_POST['cardname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards WHERE cardname = '$searchEscaped' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($result->num_rows == 1){
// only one result found, show just that
$row = $result->fetch_assoc()
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}else{
// multiple rows found, show them all
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
?>

Related

How to use ? in URL?

I am trying to figure out a way to have one PHP page to display all of my blog post but have the URL decide what post is requested from that database. Something kind of like this: localhost/bolg/posts.php?pid=1 In my database I have it set up to where each post has an ID associated with it. So what I want is something that put the pid=1 and put it in the MySQL code. Here is the PHP code of the post.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title, content, date FROM posts where id =3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Assuming you enter example.com?pid=10 in the browser address bar, you can capture that variable pid using the $_GET (docs) array which PHP automatically fills for you when a page is called with a querystring.
Using your existing code as a start point you can
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
if (isset($_GET['pid'])) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, title, content, date FROM posts where id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['pid']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
// while looop is not necessary, you are only returning one row
$row = $result->fetch_assoc();
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
$conn->close();
} else {
echo "0 results";
}
Notice I took the liberty of amending your database access code to use prepared and parameterised query and binding the values to avoid SQL Injection Attack. You should always use this technique in the future

php script not sending query to mysql db?

The below code I got from the w3 schools website and adapted it a little to my db but no matter what when I click on my search button I only get the first line printed and nothing else. It doesn't even print if the connection to my db is successfully made or not.
I used chrome's dev tool to check my network traffic and I can see my POST request made successfully:
name: bahamas
submit: Search
I enabled logging for both error and general on my mysql instance, and did a grep for bahamas and got no hits. So this would seem to indicate that the script didn't even query my db?
IE this is what I get: https://imgur.com/a/PHKBmbU
<?php echo("PHP Search Page Loaded Successfully");
if(isset($_POST['submit'])){
if(preg_match("^/[A-Za-z]+/", $_POST['name'])){
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo("We are not dead");
}
$sql = "SELECT boatname, date, price FROM liveaboards";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo("<br> boatname: ". $row["boatname"]. " - date: ". $row["date"]. " " . $row["price"] . "<br>");
}
} else {
echo(" 0 results");
}
$conn->close();
}
}else{
echo("<p>Please enter a search query</p>");
}
?>
In following the theme of W3 Schools (one of my favorite resources), here is the correct way to sanitize data: https://www.w3schools.com/php/php_filter.asp
Applied to your code:
<?php echo("PHP Search Page Loaded Successfully");
// test variables.
$_POST['submit'] = true;
$_POST['name'] = "bahamas";
if(isset($_POST['submit'])){
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo("We are not dead");
}
$sql = "SELECT boatname, date, price FROM liveaboards";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo("<br> boatname: ". $row["boatname"]. " - date: ". $row["date"]. " " . $row["price"] . "<br>");
}
} else {
echo(" 0 results");
}
$conn->close();
}else{
echo("<p>Please enter a search query</p>");
}
?>
According to your POST result, you are receiving name: bahamas submit: Search , if so then Correct this
if(isset($_POST['submit'])){
TO
if(isset($_POST['Search'])){

not able to show all records in my database

i am testing my database by executing some MySQLi statements
in this case : i want to display all the records of 2 specefic rows (name,score)
i checked how to do such thing in PHP , and i did it
problem is , the page is not showing anything at all , (blank empty page)
My code :
<?php
$servername = "sql3.freesqldatabase.com";
$username = "MY USERNAME";
$password = "MY PASSWORD";
$dbname = "MY DBNAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name,score FROM Scores");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " " . $row["score"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
and , i executed the same query in phpMyAdmin Control Panel , and it worked
What have i done wrong ?
This line
$sql = "SELECT name,score FROM Scores");
Should be
$sql = "SELECT name,score FROM Scores";
This syntax error will cause an error and your environment is likely suppressing errors/warnings.

Connecting PHP to mySQL and retrieving data

i am new to PHP, and i am attempting to create a simple connection from html to mySQL using php. I met with some problems when running my codes.
this is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["userid"]. ;
}
} else {
echo "0 results";
}
$conn->close();
?>
after running on a browser, this is displayed:
connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT username FROM users"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "
id: ". $row["userid"]. ; } } else { echo "0 results"; } $conn->close(); ?>
Do you have mysql running on your localhost machine? You must verify that it is working first before you can connect via php. Also, make sure you have TCP/IP sockets open in mysql and to make sure it isn't just listening via unix sockets.
echo "<br> id: ". $row["userid"]. ;
this is a syntax error, no need to end it with a full stop.also the correct syntax to connect to sql server is
mysqli_connect("localhost","my_user","my_password","my_db") or die("");
Debug the code before posting it here.
maybe try testing it with a try catch statement. Its what I've done. this way you can display your error messages a little more nicely. As for the cause, PressingOnAlways is probably right
If you are using wampserver or any other server you need to put your php files into c:\wamp\www folder and run them in browser by typing localhost/nameofyourfile.php (change c:\wapm\www for your server installation path or type)
you have the syntax error in blow line
echo "<br> id: ". $row["userid"]. ;
. (dot) should not be there.
second you fetch usernamestrong text by following query
$sql = "SELECT username FROM users";
but you try to get userid
echo "<br> id: ". $row["userid"]. ;
try below code.
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT usersname FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["usersname"] ;
}
} else {
echo "0 results";
}
$conn->close();
?>

How to write PHP to Mysql page

Currently I just done HTML and I trying writing PHP Script on connection Mysql, But all web site on google is confuse, because now I need specify write connection by used PHP Only,
Please could you help explain step by step on code from HTML to PHP and write PHP to MySql, Thank you very much.
There is many docs about this, but you can start from here:
http://www.w3schools.com/php/php_mysql_select.asp
And here is the example code, what i suggest you:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

Categories