adding HTML form input to database - php

Kindly need assistance in my coding, I have a database named Books with table called OpenBooks I would like to add the html form which are user inputs into the table and echo confirmation.
<?php
$Title = $_POST['Title'];
$Author = $_POST['Author'];
$Series = $_POST['Series'];
$Price =$_POST['price'];
//database connection
$connection = mysqli_connect('localhost', 'root', '','books');
if(!$connection){
die("Database connection failed");
}
$query = "INSERT INTO OpenBooks(Title,Author,series,price)";
$query .= " VALUES ('$Title', '$Author', '$series', '$price')";
$result = mysqli_query($connection, $query);
}
?>

if (!$result) {
die('Invalid query: ' . mysql_error());
}
else {
echo 'yay, done';
}
And you need $Price instead of price and rest of variables starting from capital letter.

Related

Post function is not working in 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']."')";

not response for database

This is the code for database connection in php:
<?php
$connection = mysql_connect("localhost", "root", "root"); // Establishing Connection with Server
$db = mysql_select_db("fimos", $connection); // Selecting Database from Server
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$gender = $_POST["gender"]; //declare gender
$race = $_POST["race"];
$ic = $_POST["icno"];
$name = $_POST["name"];
$old_ic = $_POST["oldic"];
$add1 = $_POST["add1"];
$add2 = $_POST["add2"];
$add3 = $_POST["add3"];
$postcode = $_POST["postco"];
$town = $_POST["tow"];
$state = $_POST["state"];
$home_con = $_POST["homep"];
$fax_contact = $_POST["fax"];
$hp_con1 = $_POST["mobi1"];
$hp_con2 = $_POST["mobi2"];
$email = $_POST["email"];
if($ic !=''||$email !=''){
//Insert Query of SQL
$query = mysql_query("INSERT INTO customer_info(cust_gender, cust_race, cust_ic,
cust_name, cust_old_ic, cust_add1, cust_add2, cust_add3, cust_postcode,
cust_town, cust_state, cust_home_con, cust_fax_contact, cust_hp_contact1,
cust_hp_contact2, cust_email)
VALUES ('$gender', '$race', '$ic' , '$name', '$old_ic', '$add1', '$add2',
'$add3', '$postcode', '$town', '$state', '$home_con', '$fax_contact',
'$hp_con1', '$hp_con2', '$email')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
mysql_close($connection); // Closing Connection with Server
Hi guys, I want to ask about the database connection, is it my code wrong somewhere?
Because I cant found any error in the code.
I click button register should come over this page to store the data.
when I come to this page display all blank.
I try to change the database name also no response.
I hope you guys can help me.
Thanks.
It should be:
$connection = mysql_connect("localhost", "root", ""); //empty the third parameter. If you have password then insert that in your third parameter
Paste this code inside your if condition so that it will return error from your sql query.
if (!$query) {
die('Invalid query: ' . mysql_error());
}
Try to use the PDO extension instead of mysql & mysqli function. The mysql_* functions are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi there are lots of benefits of using PDO over mysqli.
Add the above code
if($ic !=''||$email !=''){
$query = mysql_query("your query");
if (!$query) {
die('Invalid query: ' . mysql_error());
} else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
}

PHP Insert values into Database at certain position

So I'm currently creating a Online Game and already got the login and registering working but now I'm working on submitting Stats such as health and a player's level and retrieving that.
So in this PHP file I'm able to retrieve the info of a certain player but I don't know how to submit new stats into a certain player's row. I'm still learning PHP so please help me out.
<?php
// Database Things =========================================================
$host = "localhost";
$user = "lyth_com_Spillnk";
$password = "INTERESTED?";
$dbname = "lythumn_com_Spillnk";
mysql_connect($host, $user, $password) or die("Can't connect into database");
mysql_select_db($dbname)or die("Can't connect into database");
// =============================================================================
$Act = $_GET["Act"];// what is action, Submit or Retrieve?
$nick = $_GET["User"];
$health = $_GET["Health"];
$level = $_GET["Level"];
$xcood = $_GET["X"];
$ycood = $_GET["Y"];
if($Act == "Retrieve"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$total = mysql_num_rows($result_id);
if($total) {
$datas = #mysql_fetch_array($result_id);
echo ($datas["Health"], $datas["Level"], $datas["X"], $datas["Y"]);
}
}
if($Act == "Submit"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$query = "INSERT INTO Stats (Username, Health, Level, X, Y) VALUES('$nick', '$health', '$level', $'xcood', $'ycood')";
mysql_query($query) or die("ERROR");
mysql_close();
echo "Submitted";
}
// Close mySQL Connection
mysql_close();
?>
It's mostly concercing this piece of code:
if($Act == "Submit"){
$SQL = "SELECT * FROM Stats WHERE Username = '" . $nick . "'";
$result_id = #mysql_query($SQL) or die("DB ERROR");
$query = "INSERT INTO Stats (Username, Health, Level, X, Y) VALUES('$nick', '$health', '$level', $'xcood', $'ycood')";
mysql_query($query) or die("ERROR");
mysql_close();
echo "Submitted";
}
As you are able to see I already retrieve the Index of where the player's stats are located so how do I insert values there?
Thanks in advance!

Combining all INSERT statements into one

I'm creating a page for a class and I have lots of different while loops with lots of different INSERT statements. I didn't think there would be a problem with that until I discovered that they weren't being inputed right. They were all inputed but what happened was that they were all inputed in separate rows as opposed to being one entry across their individual columns. I need it so that all of the INSERT statements are combined into one while still checking to make sure that the full name isn't yet in the database. Please help me rewrite my code so that it can do just that.
Here is the code that needs to be rewritten so that it just has one INSERT statement:
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$name = mysql_real_escape_string($_POST['firstname']);
$query = "SELECT * FROM names_1 WHERE firstname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your first name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE lastname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your last name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (lastname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE fullname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your full name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (fullname) VALUES('$name')";
$result = mysql_query($query);
}
$age = mysql_real_escape_string($_POST['age']);
$query = "INSERT INTO names_1 (age) VALUES('$age')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else {
echo "Your name couldn't be added to the database!";
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
When inserting a row with multiple columns you can just combine the two groups of keys and values like so:
INSERT INTO names_1 (firstname, lastname) VALUES ('John', 'Smith')
The other alternative is in your database mark both the Firstname and Lastname as Unique columns. Then you can do the following.
INSERT INTO names_1 (firstname, lastname) VALUES ('John', 'Smith') ON DUPLICATE KEY UPDATE names_1 SET x="blah" WHERE blah
http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
This should accomplish what you are setting out to do.
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$fullname = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE fullname='" . $fullname . "'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your full name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname, lastname, fullname, age) VALUES('" . $_POST['firstname'] . "','" . $_POST['lastname'] . "','" . $fullname . "'," . $_POST['age'] . ")";
$result = mysql_query($query);
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css"/>
<?php include("Header.php"); ?>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>

Pinterest style of text

I'm creating a news feed site. User can upload text and then it displays the texts below eachother. I want to display all the texts in a way that Pinterest displays pictures. How can I do this?
The code for displaying and getting the text from the database is:
<?php
//connect
mysql_connect("host","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
//query the database
$getnews = mysql_query("SELECT * FROM news ORDER BY id DESC") or die(mysql_query());
while ($row = mysql_fetch_assoc($getnews))
{
//get data
$id = $row['id'];
$title = $row['title'];
$body = $row['body'];
$date = $row['date'];
echo "
<b>$title posted on $date</b><br>
";
echo nl2br($body);
echo "<hr>
";
}
?>
And the code for posting a text is like:
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('host', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if ($_POST['post'])
{
//get data
$title = $_POST['title'];
$body = $_POST['body'];
//check for existance
if ($title&&$body)
{
mysql_connect("host","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','$title','$body','$date')") or die(mysql_error());
die("Your text has been posted!");
}
else
echo "Please fill out your name and text<p>";
}
?>

Categories