Post function is not working in php - php

I'm just a beginner on php and learning how to code. I'm following a cbt nugget where I'm already on a an action to post the inserted value on a form and pass it to action page and insert to database. I getting this message when I try on the submit button
0Problems with query:
My DB connector
<?php
$host = "localhost";
$user = "root";
$password = "";
$db = "linuxcbtcontacts";
# Step 1 instantiate DB object
$conn = mysqli_connect($host,$user,"",$db) or die("Problems connecting:" . mysql_error());
#if ($conn) { echo "True"; }
#$dbselect = mysqli_select_db("linuxcbtcontacts", $conn) or die("Error selecting DB:" . mysql_error());
# Step 2 - select DB
#$dbselect = mysqli_select_db($conn, "linuxcbtcontacts") or die("Error selecting DB:" . mysql_error());
$dbselect = mysqli_select_db($conn,$db) or die("Error selecting DB:" . mysql_error());
?>
My form action page (after hitting the submit from the form)
<?php
require 'dbconnect.php';
$unique_check = "select name from contacts where name = 'name'";
$results_unique_check = mysqli_query($conn,$unique_check);
$rowcount = mysqli_num_rows($results_unique_check);
echo $rowcount;
if ($rowcount > 0) {
echo "Please use in different name", "<br>";
echo "<a href=query2.php>go back</a>";
exit(); }
else {
$query1 = "INSERT INTO contacts(name,email,age,yearborn,ratesite,industry,buyourproducts,software,hardware) VALUES('$_POST[name]','$_POST[email]','$_POST[age]','$_POST[yearborn]','$_POST[ratesite]','$_POST[industry]','$_POST[buyourproducts],'$_POST[software]','$_POST[hardware]')";
# Step 3 - invoke query
$results = mysqli_query($conn,$query1) or die("Problems with query:" . mysql_error());
$rowcount = mysqli_affected_rows($conn);
echo "Total Inserted Records:\t", $rowcount, "<br>";
}
?>
From the cbt I should get this message after the submit button was clicked
0Total Inserted Records:1
Already tweaked on all possibilities on what I saw on the internet but still i end on the "0Problems with query:" message

$query1 = "INSERT INTO contacts(name,email,age,yearborn,ratesite,industry,buyourproducts,software,hardware) VALUES('".$_POST['name']."','".$_POST['email']."','".$_POST['age']."','".$_POST['yearborn']."','".$_POST['ratesite']."','".$_POST['industry']."','".$_POST['buyourproducts']."','".$_POST['software']."','".$_POST['hardware']."')";

Related

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'])){

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

Get value from specific MySql row

On my website, a user's background URL is stored with their data in a database. I need to get this value and store it in a variable.
However, I am having trouble doing so, the code I have right now gives me an error but doesnt tell me what the error is.
My code:
<?php
error_reporting(E_ALL);
include 'config.php';
$pin = $_COOKIE["UID"];
// Create connection
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * from users where pin ='$pin'";
$result = $conn->query($query);
if ($conn->query($query) === TRUE) {
$bg_url = $row[bg_url];
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
echo $bg_url;
mysqli_close($conn);
?>
$query = "SELECT * from users where pin ='$pin'";
$result = $conn->query($query);
Actually yes, the John's answer is correct, you're not using the return values properly, but you are neither accesing the variables properly, for example, I don't see where $row comes from. Try this and change it for array mode if you need to. I'm not very used to mysqli_* API, because I use PDO mostly.
if ($result) {
while($row = $result->fetch_object()) {
$bg_url = $row->bg_url;
}
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
echo $bg_url;

Query MySQL table based on form post

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.

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.

Categories