hi in want to build a registration and lottery app with php
i want to make a users id in my prize table upon registration of users and i want to add to a number of my buy_count when users buy a ticket...
so i got 2 tables :
prize , users
prize : users_id , buy_count
users : fn , ln , pass...usual staff
this is the sctipt for users reg form :
$sql = 'INSERT INTO users (id,fn,ls,psw) VALUES (:id,:fn,:ln,:psw);
INSERT INTO prize (user_id, buy_count) VALUES (LAST_INSERT_ID(), 4)';
script gives me an error , whats wrong with it ? i want to add to users id in prize table upon user registration , whats the problem with my query ?
whats the right way to do this ?
UPDATED :
so now this is my code :
<?php
try {
require_once 'inc/connect.php';
$sql =("
INSERT INTO users (fn,ls,psw) VALUES (:fn,:ln,:psw);
INSERT INTO prize (user_id) VALUES (LAST_INSERT_ID());
");
$form = $_POST;
$fn = $form['fn'];
$ln = $form['ln'];
$psw = $form['psw'];
$values = array(
':fn' => $fn ,
':ln' => $ln ,
':psw' => $psw
);
$stmt = $db->prepare($sql);
$stmt->execute($values);
if ( $stmt ){
echo "<p>Thank you. You have been registered</p>";
} else {
echo "<p>Sorry, there has been a problem inserting your details. Please contact admin.</p>";
}
$errorInfo = $db->errorInfo();
if (isset($errorInfo[2])){
$error = $errorInfo[2];
}
} catch (Exception $e) {
$error = $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Connection with PDO</title>
<link href="../../styles/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Connecting with PDO</h1>
<?php if(isset($error)) {
echo "<p>$error</p>";
}else {
?>
<?php
if ( empty( $_POST ) ) {
?>
<h1>Registration</h1>
<form name="" action="" method="POST">
<label for 'username'>Username: </label>
<input type="text" name="fn"/>
<label for 'password'>Password: </label>
<input type="password" name="psw"/>
<label for 'first_name'>First name: </label>
<input type="text" name="fn"/>
<br/>
<button type="submit">Submit</button>
</form>
<?php
} else {
print_r( $_POST );
}
?>
<?php } //error ?>
</body>
</html>
still doesnt do what i want ... doesnt add any data to the tables and AI users_id with last I I
anyone can help with this ?
Short answer: RTM
Long answer (from the mysql documentation) When a new AUTO_INCREMENT value has been generated, you can also obtain it by executing a SELECT LAST_INSERT_ID() statement
You are not generating a new ID automatically, you are specifying the value directly. So you can do one of two things, remove the id column and value :id placeholder from your first query OR use the same :id placeholder in your second query.
Related
What am doing wrong ?
this might be the simple solution to all experts here, but i have tried all the ways and i dont know where is my mistake ?
The idea is to add and items through my page to my database and then i can check them as todo list or to buy list. As well is in future this will be toBuy/toDo list web application so whole family members add items and in the end of the day one refresh the page and get the whole items in the database fetched!
my codes are below:
TodoTobuy.php
<?php
include("includes/header.php");
include("./forms/fadd-items.php")
?>
<?php
try {
//Tiedot kantaan
/* var_dump($_POST); */
$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount, id) VALUES (:items, :amount, :id);");
$STH->execute($data1);
$data4['id'] = $data1['id'];
$sql4 = "SELECT id FROM todoORtobuy where id =:id ORDER BY start DESC LIMIT 50";
$kysely4 = $DBH->prepare($sql4);
$kysely4->execute($data4);
$tulos2 = $kysely4->fetch();
$_SESSION["startDate"] = $tulos2[0];
} catch (PDOException $e) {
echo "Yhteysvirhe: " . $e->getMessage();
file_put_contents('log/DBErrors.txt', 'Connection: ' . $e->getMessage() . "\n", FILE_APPEND);
}
?>
My form
<fieldset>
<form method="post">
<p>
Items toDo \ toBuy:
<br /> <input type="text" name="givenItems" placeholder="Write what toDO\toBuy..." maxlength="100"/>
</p><p>
Amount needed:
<br /> <input type="text" name="givenAmount" placeholder="Write amount of what to buy..." maxlength="100"/>
</p>
<br /> <div>
<input type="submit" name="submitUser" value="Add" id="send" class="sendbutton"/>
</div>
</p>
</form>
</fieldset>
error i get is: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I mean i kindda understand the error, but cant find the mistake! Thank you for helping in advance
$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount) VALUES (:items, :amount);");
$STH->execute($data1);
In your code you are using 3 prepared values for your query but you only pass 2.
Also when inserting you don't need to insert the id, it should be set as auto-increment in your table and basically takes care of itself for each record you insert.
That how it worked i commented those in lower part, whichwas not needed.
thank you #pr1nc3
<?php
try {
//Tiedot kantaan
/* var_dump($_POST); */
$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount) VALUES (:items, :amount);");
$STH->execute($data1);
/* $data1['id'] = $data1['id'];
$sql4 = "SELECT id FROM todoORtobuy where id =:id ORDER BY start DESC LIMIT 50"; */
/* $kysely4 = $DBH->prepare($sql4);
$kysely4->execute($data1);
$tulos2 = $kysely4->fetch();
*/
} catch (PDOException $e) {
echo "Yhteysvirhe: " . $e->getMessage();
file_put_contents('log/DBErrors.txt', 'Connection: ' . $e->getMessage() . "\n", FILE_APPEND);
}
?>
I am new to PHP/MYSQLI and I am having trouble creating a simple search to search my database. The columns in my database are: 'ID' , 'Name' , 'Age'. The name of my database is 'users' and the table name is 'employees'.
Here is the code:
<?php require('Connections/Localhost.php'); ?>
<?php
if (isset($_POST['Search'])) {
$search = $_POST['element'];
$sql = mysqli_query("SELECT * FROM employees WHERE Name = '$search' ");
if($sql->num_rows > 0 ) {
while($rows = $sql->fetch_assoc()) {
$id = $rows['ID'];
$name = $rows['Name'];
$age = $rows['Age'];
echo "ID: $id <br> Name: $name <br> Age: $age <br>";
}
}
else {
echo "No Result Found!";
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form method="post">
<input type="text" name="element" placeholder="Enter A Name"/>
<input type="button" name="Search" value="Search" />
</form>
</body>
</html>
It just returns a blank page and nothing else. I want the user to enter a name in the text area of the form and on clicking the Search button all the data corresponding to that name from the database should be displayed on the webpage. Please correct me where I made the mistake.
You need to change button type to submit.
Your form is not posting.
Change
<input type="button" name="Search" value="Search" />
To:
<input type="submit" name="Search" value="Search" />
Also, mysqli_query() needs database connection resource.
You have given only sql query.
$sql = mysqli_query($databaseConnection, "SELECT * FROM employees WHERE Name = '$search' ");
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode =
MYSQLI_STORE_RESULT ] )
Reference
As per request of OP here I will explain the general concept of a Prepared statement in mysqli feel free to edit this if you feel I did not elaborated on a topic.
The first thing you need to do is prepare the query(preparing the
query is sending an empty query to the database). But instead of
defining the parameter you will put a question mark.
After that you need to bind the parameters to the question marks In the exact order as in the query! The first thing you'll do is defining the type of the parameter string is s integer is i and blob
is b. After that you'll need to define the variables with the data.
And the third and final thing you'll need to do is executing the query. I always use it in an if statement because it will return a
true or false and like this you can check if the query failed or not and handle the error. In this case you will not need an else because the page will die if the query returns false.
/*1.*/
$stmt = $databaseConnection->prepare("SELECT * FROM `employees` WHERE `name` = ?");
/*2.*/
$stmt->bind_param("s",$search);
/*3.*/
if(!$stmt->execute())
{
die("There went something wrong: " . $stmt->error);
}
Edit: here is the question explaining more about how to prevent SQL-injections.
Requesting some help on this task management system that i am making for class. I cant quite get it to work right. information is sometimes lost before it gets to the server and some of the last php code leeks thru to being seen on the site. can anyone tell me what i am doing wrong and help me to fix this? this code is supposed to allow you to send the task to a data base and the managing section relays the data from the database to the webpage.
data base is set up as this
3 Columns:
id - INT - 5 Length - Primary Key - AI.
description - VARCHAR - 255 Length.
active - BOOLEAN - 1 Length.
I am creating this on the hostica text editor that is within the site not an IDE if there are any discrepancy in the code
the website link is http://jtaylor84.net/taskmanager.php
I would like this code to work to take the information entered and relay it to the database and show in the managed tasks in order to have them up to be removed and show the tasks that have been entered.
<!DOCTYPE html>
<html>
<head>
<title>Online Task Manager</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="main">
<?php
$con = mysqli_connect('localhost', 'root', '', 'Jhonny3_Task_Manager') or die(mysql_error());
if (isSet($_POST['createTask'])) {
if (isSet($_POST['desc']) && $_POST['desc'] != '') {
$desc = $_POST['desc'];
$q = mysqli_query($con, "INSERT INTO `tasks` VALUES ('', '$desc', '1')") or die(mysql_error());
if ($q) { echo 'Added task.';
}else
echo 'Failed to add task.';}}
if (isSet($_GET['removeTask']) && isSet($_GET['id'])) {
$id = $_GET['id'];
$q = mysqli_query($con, "UPDATE `tasks` SET `active`='0' WHERE `id`='$id'");
if ($q) { echo 'Task removed.';
}else
echo 'Failed to remove task.';}
?>
<h1>Add Task:</h1>
<form action='taskmanager.php' method='POST'>
Description of Task: <input type='text' name='desc'/>
<input type='submit' value='Create Task' name='createTask'/>
</form>
<h1>Manage Tasks:</h1>
<?php
$qu = mysqli_query($con, "SELECT * FROM `tasks` WHERE `active`='1'");
if (mysqli_num_rows($qu) > 0) {
after this section the code shows up on the web page and i am not sure why
while ($row = mysqli_fetch_array($qu)) {
echo "";
echo $row['description'];
echo "<a href='taskmanager.php?removeTask&id=".$row['id']."'>Remove Task</a>";
}
}
?>
<footer id="foot01"></footer>
</div>
<script src="sitescript.js"></script>
</body>
</html> `
Problem might be your php server .your code working fine in my server .
I'm creating this web page for this class that I'm in and for it I need to concatenate two separate HTML form inputs with a space in between and insert them into a MySQL database. Specifically I ask the user for their first name and their last name in separate HTML form inputs and I have to concatenate those two input into a full name with a space in between (or else "Bob" and "Ross" concatenated would be "BobRoss" instead of "Bob Ross"). I don't know where to start when doing that. Also I need to check that the full name isn't already in the database before inserting it into the database, but I'm already doing that with the first name and last name so that shouldn't be too hard.
Here is the HTML page with the form inputs:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<p>First name:</p><input type="text" name="firstname"><br>
<p>Last name:</p><input type="text" name="lastname"><br>
<p>Age:</p><input type="text" name="age"><br>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
And here is the PHP page where it inputs the data into the database. Currently I'm inputing the user's first name, last name, and age, but I need to concatenate the first and last name and make sure it isn't in the database and then insert it into the database and I haven't done that. Currently I make sure that the first name is unique, I make sure that the last name is unique, but I don't care whether the age is unique or not.
<?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 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 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['age']);
$query = "INSERT INTO names_1 (age) VALUES('$name')";
$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>
For a start you shouldn't be using mysql functions as this extension
is deprecated as of PHP 5.5.0, and will be removed in the future.
I suggest using the new improved PDO library and PDO Prepared Statements, see here.
As for the concatenation, you could simply do it like this:
$concatenated_name = $_POST['firstname'] . " " . $_POST['lastname'];
This would concatenate the names with a space in between.
You can then use $concatenated_name in your queries.
However I still strongly recommend you use PDO for all your functions.
$fullname = trim($_REQUEST['firstname']).trim($_REQUEST['lastname']);
I'm trying to make a simple product page (no login or anything like that) in php and mysql.
So far, everything shows up on my products page fine, I can delete/add just fine from my admin page. From there I'm trying to figure out how to create an edit function.
So I made a form that populates from the mysql table based on the productid for convenience (edit2.php?id=X) which then posts to edit.php and hopefully updates the database.
So far, reusing the old code isn't working, somehow I was hoping it would be that simple.
This is my add product (which works) :
<?php
session_start();
if(isset($_POST) && isset($_POST['hp']) && empty($_POST['hp'])) {
if(
isset($_SESSION['token']) &&
$_SESSION['token'] == $_POST['token']
) {
mysql_connect('localhost', 'test_admin', 'test');
mysql_select_db('test_product');
$data = array_map('mysql_real_escape_string', $_POST);
$query = "
INSERT INTO products (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
";
if(mysql_query($query)) {
echo '<p>Your information was successfully saved.</p>';
unset($_SESSION['token']);
} else {
echo '<p>There was an error storing your data, please try again later.</p>';
}
} else {
echo '<p>Your data has already been saved.</p>';
}
} else {
echo '<p>Error.<br />Please try again later.</p>';
}
?>
This is my update (which just throws out a syntax error or 'error storing your data' :
<?php
mysql_connect('localhost', 'test_admin', 'test');
mysql_select_db('lbriedis_product');
$data = array_map('mysql_real_escape_string', $_POST);
$query = "UPDATE products WHERE id = ".$pageid." (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
";
if(mysql_query($query)) {
echo '<p>Your information was successfully saved.</p>';
unset($_SESSION['token']);
} else {
echo '<p>There was an error storing your data, please try again later.</p>';
echo mysql_error(); //Used for development and testing only
}
?>
I get session errors when I attempt to use session validation probably because I start a session on my admin page (add product form is on admin.php, edit and delete are links) ?
Nevertheless, I removed the session checks for the moment as I'm struggling more so with the update part.
Also I'm not sure of the best way to pass $pageid to the update query for 'update where id = $pageid. I have a hidden field with the value (see edit form), how do I reference this correctly?
Edit form (values display correctly so where id = $pageid is working here:
<?php
$dol = "$";
$pageid = (int)$_GET['id'];
mysql_connect('localhost', 'lbriedis_admin', 'xxxxxx123');
mysql_select_db('lbriedis_product');
$result = mysql_query("SELECT * FROM products WHERE id = ".$pageid."");
if($result){
$data = mysql_fetch_assoc($result);
}
?>
<form id="inputForm" method="post" action="edit.php">
<fieldset>
<label>Pool name:</label>
<?php
echo '<input type="text" name="product_name" value="'.$data['pool_name'].'" />';
?>
<label>Price:</label> <br>
<?php
echo '$ <input type="text" name="price" value="'.$data['price'].'" />';
?> <br />
<label>Description:</label>
<?php
echo '<textarea name="description">'.$data['description'].'</textarea>';
?>
<label>Image:</label></label>
<?php
echo '<input type="text" name="image" value="'.$data['image'].'" />';
?>
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
<input type="text" id="hp" name="hp" />
<?php
echo '$ <input type="hidden" name="$pageid" value="'.$pageid.'" />';
?>
<br>
<input type="submit" name="submit" value="Update" />
</fieldset>
</form>
your update query have incorrect sintax
$query = "UPDATE products WHERE id = ".$pageid." (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
correct sintax should be
$query="UPDATE products SET
product_name = '".$data['product_name']."',
price ='".$data['price']."',
description = '".$data['description']."',
image = '".$data['image']."'
WHERE id = '".$pageid."'
change this
name="$pageid"
to
name="pageid"
and access it like this
$data = array_map('mysql_real_escape_string', $_POST);
$query = "UPDATE products WHERE id = {$data['pageid']} (
the problem was $pageid was not accessible in edit.php. And you have assigned $pageid to name attribute , which will be different fot each product.
Change the query to this
$query="UPDATE products SET
product_name = '{$data['product_name']}',
price ='{$data['price']}',
description = '{$data['description']}',
image = '{$data['image']}'
WHERE id = '{$data['pageid']}'
replace your update query with the below:-
$query = "UPDATE products
set product_name=$data['product_name'],
price = $data['price'],
description = $data['description'] ,
image = $data['image']
where id =". $pageid ;