Combining all INSERT statements into one - php

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>

Related

adding data with PHP to the db is not working

I'm using MAMP an my PHP won't add data to the db
I have looked at other similar questions and done everything on them, yet it still is not working.
I am using MAMP and I've done everything right as far as I know but the problem is the same no matter what I do.
<?php
require_once('dbconnect.php');
$email = $_GET['email'];
$name = $_GET['name'];
$message = $_GET['message'];
$my_query = "";
$my_query = "select * from Users where email = '$email' ";
$my_query = "INSERT INTO Users (email, name, message) VALUES ('$email', '$name', '$message')";
$result = mysqli_query($connection, $my_query );
if($result)
{
echo "Successfully Sent!";
}
else
{
echo "<b>ERROR: unable to post </b>";
}
}
mysqli_close();
?>
Here use this code and and tell what is the error
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO Users (email, name, message) VALUES ('$email', '$name', '$message')"))
{
echo("Error description: " . mysqli_error($con));
}
mysqli_close($con);
?>
if you dont get any error or blank value in db use your values like
values('".$email."', '".$name."', '".$message."')"
in db It will be executed like values('test.abc.com', 'abc', 'It is working')

adding HTML form input to database

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.

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!

Do Not Duplicate VALUE if already exist on MySQL

I've been trying to accomplish this, but as other issues I just can't figured it out. I've been reading around for posibles solutions but non of them goes along with my code, or if they do I can't figure out how or where to use them.
I have a DB where a user sends records. The database consist in few tables containing the Following "Name, Lastname, Phone". If any of this values is duplicate, I would like my code to identify and Ignore the submission of the Form if ALL this VALUES already exist on the DB.
Here is my code:
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$_POST[Name]','$_POST[LastName]','$_POST[Phone]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
mysql_close($con);
?>
The mysql_* function are all deprecated now, and should NEVER be used. change your code to do something like the following:
//Set up a PDO connection to MySQL
$host = 'host_name';
$dbname = 'database_name';
$user = 'user_name';
$pass = 'user_pass';
try
{
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
//Determine whether the appropriate values have been passed.
if(isset($_POST['Name']))
{
$name = $_POST['Name'];
}
else
{
echo "You must provide a name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['LastName']))
{
$name = $_POST['LastName'];
}
else
{
echo "You must provide a last name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['Phone']))
{
$name = $_POST['Phone'];
}
else
{
echo "You must provide a phone number!";
exit; //This may not be what you want to do here, it's an example action
}
//Set up the query using anonymous values
$sql="INSERT INTO people (Name, LastName, Phone) VALUES ('?','?','?')";
$sth = $DB->prepare($sql);
try
{
//Attempt to execute the insert statement
$sth->execute(array($_POST[Name], $_POST[LastName], $_POST[Phone]));
echo "Record Added";
}
catch(PDOException $e)
{
//If the insert failed, then you can handle the error, and determine
//what further steps need to be taken.
echo "Record Not Added";
}
Here's another question with a similar setting, that may also be useful to you:
https://stackoverflow.com/a/10414922/1507210
search in the table before insert
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$name = mysql_real_escape_string($_POST[Name]);
$LastName= mysql_real_escape_string($_POST[LastName]);
$Phone= mysql_real_escape_string($_POST[Phone]);
$search_res=mysql_query("SELECT * from people where Name='$Name' OR LastName='$LastName' OR Phone='$Phone'");
if(mysql_num_rows($search_res) < 1){
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$Name','$LastName','$Phone')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
}else{
echo "User Already exits";
}
mysql_close($con);
?>
Try this easy solution
$result = mysql_query("SELECT * FROM TABLE WHERE Column = 'value' ");
if( mysql_num_rows($result) < 1) {
mysql_query("INSERT INTO table (column) VALUES ('value') ");
}

User authentication using php and mySql

Am facing challenges in the following code; please help:
<?php
session_start();
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$db_exist = mysql_select_db("seta", $con);
$myUName = $_POST["username"];
$myPwd = $_POST["pwd"];
$loFmUname = strtolower($myUName);
if($db_exist){
$sql = "SELECT * FROM Persons WHERE $loFmUname = 'strtolower($db_field['UserName'])' AND $myPwd = '$db_field['UserPwd']'";
$result = mysql_query($sql);
if($result){
$_session['loged'] = '$loFmUname';
header('location:index.html');
die();
}
else{
echo"Invalid username and/or password please";
echo "<a href='login.php'>try again</a>";
}
}
else{
echo "Sorry Database Not Found";
}
mysql_close($con);
?>
The error is coming on line 15.
Note that strtolower() is being used to ignore case-sensitive username.
Change the line
$sql = "SELECT * FROM Persons WHERE $loFmUname = 'strtolower($db_field['UserName'])' AND $myPwd = '$db_field['UserPwd']'";
By this one
$sql = "SELECT * FROM Persons WHERE $loFmUname = '".strtolower($db_field['UserName'])."' AND $myPwd = '".$db_field['UserPwd']."'";
This may help you.
Thanks
You need to use dot separators when doing manipulation to a variable inside a variable.
Also, should $_SESSION['loged'] = '$loFmUname'; be that, or $_SESSION['logged'] = '$loFmUname';?
<?php
session_start();
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$db_exist = mysql_select_db("seta", $con);
$myUName = $_POST["username"];
$myPwd = $_POST["pwd"];
$loFmUname = strtolower($myUName);
if($db_exist){
$result = mysql_query("SELECT * FROM Persons WHERE $loFmUname='" . strtolower($db_field['UserName']) . "' AND $myPwd='$db_field['UserPwd']' ");
if($result){
$_SESSION['loged'] = '$loFmUname';
header('Location: index.html');
die();
} else {
echo "Invalid username and/or password please";
echo "<a href='login.php'>try again</a>";
}
} else {
echo "Sorry Database Not Found";
}
mysql_close($con);
?>

Categories