Query MySQL table based on form post - php

I'm working on a web form that allows the user to conduct a zip code search. My intent is to use the form post to search a MySQL table for the matching zip code then return content from an associated field in the same row.
I can get as far as... form submits and directs user to the intended form_post.php page. If I enter <?php echo $_POST["zipcode"]; ?> on the page it returns the content submitted by the user.
I followed the PHP/MySQLi examples from these pages:
http://www.w3schools.com
/php/php_mysql_connect.asp
/php/php_mysql_select.asp
/php/php_if_else.asp
I am able to connect to the database and return the 2 selected values from the table. This is my example so far:
<?php
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
if (isset($_POST['zipcode'])) {
$zipcode = $_POST['zipcode'];
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT zip_code, area FROM zipcode_table WHERE zip_code = $zipcode";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Result: " . $row["zip_code"]. " " . $row["area"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
After the query returns the associated values I would like to determine if the returned value from 'area' is one of 3 values then forward the user to the appropriate url.
I was working on an if/else statement as follows then got stuck.
if($result == "A") {
header("Location: http://example.com/page-1/");
}
elseif($result == "B") {
header("Location: http://example.com/page-2/");
}
elseif($result == "C") {
header("Location: http://example.com/page-3/");
} else {
header("Location: http://example.com/");
exit();
}
Any recommendations are appreciated.

you are using $result in if but, you not assign it area region.So, first relpace this:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Result: " . $row["zip_code"]. " " . $row["area"]. "<br>";
}
} else {
echo "0 results";
}
with this:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Result: " . $row["zip_code"]. " " . $row["area"]. "<br>";
$result = $row["area"];
break;
}
} else {
echo "0 results";
$result = "";
}
then replace query:
$sql = "SELECT zip_code, area FROM zipcode_table WHERE zip_code = $zipcode";
with this:
$sql = "SELECT zip_code, area FROM zipcode_table WHERE zip_code = '$zipcode'";
then your problem will be solved.

Related

Display specific data for specific ids and a different data for other ids

I'm trying to achieve something with php. I have two address on my admin table I'll like to display to my users. I want to display one of the address (id equals 3) to some specific user ids and the other address (id equals 4) to every other users id. Check my code below
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "user";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = "SELECT * FROM users WHERE id = '".$_SESSION['user']."'";
if ( ($id != 11303) && ($id != 27)) {
$sql = "SELECT address FROM admin WHERE id='3'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "" . $row["address"]. "";
}
} else {
echo "0 results";
}
}
else {
$sql = "SELECT address FROM admin WHERE id='4'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "" . $row["address"]. "";
}
} else {
echo "0 results";
}
}
$conn->close();
?>
I tried getting user id from their session then i used "if" to check if their session id equals to some specific ids then select the address with id 3 from the admin table and display it "else" it displays the address with id 4. But it's displaying the address with id 3 to everyone. Please can anyone help out?
Before use $_SESSION write start_session() at the top of your code.
then try:
$sql = mysqli_query($conn,"SELECT * FROM users WHERE id = '".$_SESSION['user']."'");
$result = mysqli_fetch_assoc($sql);
$id = $result['id'];
Now, Put $id value in your condition
if ( ($id != 11303) && ($id != 27))
{
//do something
}

Accessing two tables within same statement?

I'm trying to create an upvote system where, after checking to see if you're logged in and after getting your userid, it checks if the table has your userid with the postid already in it and if it does then it means it was already upvoted. I just want to know what's wrong in my code, this is being used for learning, I don't need any complex thing.
Code:
if (isset($_GET['upvote'])) {
if ($_SESSION["loggedin"] == true) {
$upvoteid = $_GET["upvote"];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM users WHERE username=".$_SESSION["loggedinusername"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userid = $row["id"];
}
$sql2 = "SELECT userid, postid FROM upvotedposts WHERE userid='".$userid."' AND postid='".$upvoteid."'";
$result2 = $conn->query($sql);
if (!$result2->numrows > 0) {
$sql = "UPDATE posts SET upvotes = upvotes + 1 WHERE id = ".$upvoteid;
if ($conn->query($sql) === TRUE) {
echo "Sucessfully upvoted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
} else {
echo "Failed;
}
$conn->close();
}
}
When I do click the upvote button, it simply does nothing. The issue here is that as far as I know it looks like it would work but I may be forgetting something that I am unaware of or incorrectly using something.
You are missing a closing "
echo "Failed;
should be:
echo "Failed";

Using data from sql table within condition in PHP

I am very new to coding.
I am trying to select data from a table in SQL then use this data as part of a condition in a PHP If statement. The code I am using appears below. The echo $row["endsequence"]; line shows the correct value has been retrieved from the database, but the record isn't being updated as I need it to be in the final part of code. Any help much appreciated.
<?php
$result = filter_var($_GET['result'], FILTER_SANITIZE_STRING);
$action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
$pupilid = filter_var($_GET['pupilid'], FILTER_SANITIZE_NUMBER_INT);
$pathwayid = filter_var($_GET['pathwayid'], FILTER_SANITIZE_NUMBER_INT);
$stageid = filter_var($_GET['stageid'], FILTER_SANITIZE_NUMBER_INT);
$resourceid = filter_var($_GET['resourceid'], FILTER_SANITIZE_NUMBER_INT);
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "planit";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT endsequence FROM resources WHERE id= " . $resourceid;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["endsequence"];
}
} else {
echo "0 results";
}
if ($result == 'fail' && $action == 'tryagain' && $row['endsequence'] == "2") {
$sql1 = "UPDATE pupils SET activeresourceid = (SELECT nextresourceid FROM resources WHERE id=$resourceid) WHERE id=$pupilid";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
if ($conn->query($sql1) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
mysqli_close($conn);
?>

PHP / MySql if '1' echo "Ok" else if '0' echo "No"

Phpmyadmin:
Phpmyadmin Image example
if (mysql_query("SELECT setup FROM users") === 1) {
echo "One";
} else if (mysql_query("SELECT setup FROM users") === 0) {
echo "Zero";
}
On register. As defined: 0.
If table shows 0, echo Zero.
Else if table shows ID 1, echo One.
How is this done?
Solution:
$setup = mysql_query("SELECT setup FROM users");
$row = mysql_fetch_assoc($setup);
if ($row['setup'] == 0) {
echo "Zero.";
} else {
echo "One!";
}
I think you need this
First of all use mysqli
//$connection = your mysqli connection. Dont use mysql
Then properly write query if you need admin row
$query = "SELECT `setup` FROM `users` WHERE `user_id`=1 AND `username` = 'admin'";
Then execute query
$result = mysqli_query($connection, $query);
Then search for $setup value
while($row = mysqli_fetch_assoc($result)){
$setup = $row['setup'];
}
Then echo what you need
if ($setup == 1) {
echo "One";
} else if ($setup == 0) {
echo "Zero";
}
See the docs. The 'Example (MySQLi Procedural)' example is similar to what you want.
Snippet:
<?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);
?>
Changing
$sql = "SELECT id, firstname, lastname FROM MyGuests";
to
$sql = "SELECT setup FROM users";
then
if (mysqli_num_rows($result) > 0) {
to your various if checks should suffice. Not the cleanest. Seems like you could just print out the value of setup? Good luck!

Getting User Data Based on Their Information

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();
?>

Categories