I am stuck in a very crucial part of my project and would like some help - however I seem to be stuck in the PHP / SQL syntax and cannot get the query to work.
HTML code:
<form name="homepage" method="POST" action="" >
<p>Page Title</p>
<input id="pagetitle" type="text" name="home_title" value="<?php select_text("SELECT fieldcontent FROM content WHERE name='home_title'", "fieldcontent") ?>"/>
<p>Paragraph</p>
<textarea id="paragraph" name="home_text"><?php select_text("SELECT fieldcontent FROM content WHERE name='home_text'", "fieldcontent") ?> </textarea>
<h1>Images</h1>
<div id="image">
<?php select_image("SELECT * FROM `image` WHERE image_cat_id = 8"); ?>
</div>
<button name="homesavebtn" id="home-save-btn" type="submit">Save Updates</button>
</form>
PHP code - Select data
function select_text($sql, $echo) {
include 'connect.php';
$result = $conn->query($sql);
if ($result->num_rows > 0);
while ($row = $result->fetch_assoc()) {
echo $row[$echo];
$conn->close();
}
}
PHP code - update
if ($_POST) {
if (isset($_POST['homesavebtn'])){
$home_title = (isset($_POST['home_title']) ? $_POST['home_title'] : null);
$home_text = (isset($_POST['home_text']) ? $_POST['home_text'] : null);
include 'connect.php';
$sql = "INSERT INTO content(name, fieldcontent) VALUES ('home_title', '$home_title') ON DUPLICATE KEY UPDATE fieldcontent = '$home_title'";
$sql .= "INSERT INTO content(name, fieldcontent) VALUES ('home_text', '$home_text') ON DUPLICATE KEY UPDATE fieldcontent = '$home_text'";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "" . $sql . "<br>" .mysqli_error($conn);
}
$conn->close();
}
}
Getting the following error:
INSERT INTO content(name, fieldcontent) VALUES ('home_title', 'Mosta Cycling Club') ON DUPLICATE KEY UPDATE fieldcontent = 'Mosta Cycling Club'INSERT INTO content(name, fieldcontent) VALUES ('home_text', '') ON DUPLICATE KEY UPDATE fieldcontent = ''
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO content(name, fieldcontent) VALUES ('home_text', '') ON DUPLICATE KE' at line 1
You could use VALUES to get the new value you are using in the update portion. Also, if you use prepare and bind_param you will prevent SQL injection:
$mysqli = new mysqli('host', 'user', 'password', 'db');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO content(name, fieldcontent)
VALUES ('home_title', ?), ('home_text', ?)
ON DUPLICATE KEY UPDATE fieldcontent = VALUES(fieldcontent)");
$stmt->bind_param('ss', $home_title, $home_text);
$stmt->execute();
Your second SQL statement is being added to your first creating one long statement that doesn't make sense. Separate these into two different statements.
Related
I have a table with input of type time and I want to check first if there is a row with the current date and the id of employee, if it was I update the value of the input if not I insert a new row. This is what I have tried but it always inserts a new row even if the condition exists:
<?php
$E1=$_POST['E1'];
$connect = mysqli_connect("localhost", "root", "ntr-ktb123", "absence");
$sql1="SELECT * FROM retards WHERE Date ='Curdate()' AND
IdEmpl='".$_POST["IdEmp"]."' ;";
$result1=mysqli_query($connect,$sql1);
if(!$result1){
die('ERREUR SQL ! <br>'.$sql.'<br>'.mysqli_error());}
if($dt=mysqli_fetch_array($result1,MYSQLI_ASSOC)){
$sql="update retards set E1='$E1' where IdEmpl='".$_POST["IdEmp"]."' AND
Date=CURDATE();";
}
else{
$sql="insert into retards(IdEmpl,Date,E1) values
('".$_POST["IdEmp"]."',CURDATE(),'$E1'); ";
}
$result = mysqli_query($connect, $sql);
if (!$result)
{
echo("Error description: " . mysqli_error($connect));
}
else {
$message ="Effectué avec succès!";
echo "<script type='text/javascript'>alert('$message'); </script>";
}
mysqli_close($connect);
?>
This is known as an upsert which can be done in mysql using the insert ... on duplicate key update syntax.
insert into t (a, b, c) values (?, ?, ?)
on duplicate key update b = ?
Your table should have an appropriate unique index or primary key defined on the column(s) of interest.
Let's start that I am newbie in php, so still I am trying to learn. I have created a form on Wordpress and I want to insert the values on one table (data_test table, i have managed that) and then take all the columns from data_test table(id that is auto increment number,name,email,product, quantity that the user enter) and insert to other table. I used this html code for the form to parse the values:
<form action="../enter_data_insert.php" method="post" onsubmit="return form_validation()" name="myForm">
Name <input id="name" name="name" type="text" />
Email <input id="email" name="email" required type="email"/>
Product<input id="prod" name="prod" required type="text" />
Quantity<input id="quant" name="quant" required type="number" min="1" / >
<input type="submit" value="Submit" />
</form>
And then this php to take the values:
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$id = intval($value->id);
$_SESSION['myid'] = $value->id;
var_dump($value);
//insert data on data_test_ins table
$sql="INSERT INTO site_db.data_test_ins` ( id,name , email, prod,quant) VALUES ( $id,'$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
// header("Location: http://localhost/site/");
}
}
}
}
}
?>
Now it inserts all the values except the id on data_test table, i guess that it is null because it must close the first insert on php and then i have to call a second insert (with //insert data on data_test_ins table) on other php?
But i am not sure, can anyone help me please? or just guide me what is the right way to do.
I start to think that i have to create two php to parse the values and take on the first table and then on the other php to insert the values?
Any thoughts are helpful! :-)
What you are doing is not right. It is not a good approach to add value to id field to the database manually. It should be generated automatically by the database. What I would recommend is, add another field to your data_test_ins table eg: test_id which points to the id of your data_test table. This is the concept of foreign key.
Read about the concept of foreign keys here
Your code would now be:-
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$id = $value->id;
//insert data on data_test_ins table
$sql="INSERT INTO `site_db`.`data_test_ins` ( `id`,`name` , `email`, `prod`,`quant`, `test_id`) VALUES ('$name','$email','$prod','$quant', '$id')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
header("Location: http://localhost/site/");
}
}
}
}
}
?>
have you tried passing $value->id into the query instead of $value?
its an object which has the current row of a result set, so you should only pass the id attribute of this object.
$sql="INSERT INTO `site_db`.`data_test_ins` ( `id`,`name` , `email`, `prod`,`quant`) VALUES ( '$value->id','$name','$email','$prod','$quant')";
Addition:
stop using the mysql deprecated library.
you should check the posted data if its isset or not
EDIT:
your code should looks like:
<?php
if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["prod"]) && !empty($_POST["quant"])){
//connect with database
include "database_conn.php";
//get the form elements and store them in variables
session_start();
$name=$_POST["name"];
$email=$_POST["email"];
$prod=$_POST["prod"];
$quant=$_POST["quant"];
//insert data on data_test table
$sql="INSERT INTO `site_db`.`data_test` ( `name` , `email`, `prod`,`quant`) VALUES ( '$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//retrieve data
$sql = "SELECT data_test_id FROM data_test WHERE prod='$prod'";
$result = mysqli_query($con,$sql);
if(!$result){
echo mysqli_error($con);
} else{
while($value = mysqli_fetch_object($result)){
$_SESSION['myid'] = $value->data_test_id;
$id = intval($value->data_test_id);
//insert data on data_test_ins table
$sql="INSERT INTO `site_db`.`data_test_ins` ( id,name , email, prod,quant) VALUES ( '$id','$name','$email','$prod','$quant')";
if(!mysqli_query($con,$sql)){
echo mysqli_error($con);
} else{
//Redirects to the specified page
header("Location: http://localhost/site/");
}
}
}
}
}
?>
I've been trying to insert some data into my database for an events page. I have an html form and a seperate script, as seen below and the submit seems to go through for the ename id and imgsrc values but nothing past that. Anything more and I get a You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'when, descr, positions) VALUES (test, 1 ,www.vzdc.org,2017-1-20 23:59:00' at line 1I've done some reasearch but maybe it's just a weird error on my end? I'm fairly new to mysql and I would love some help! Thanks, code below.
<!-- HTML form -->
<form id="newevent" action="insertevent.php" method="post">
<p>Event Name:</p><input name="ename" type="text" width="100">
<p>ID:</p><input name="id" type="text" size="5">
<p>Banner Link:</p><input name="imgsrc" type="text" size="50">
<p>Description</p><input name="descr" type="text" height="1000px" >
<p>Date / Time (yyyy-mm-dd HH:MM:SS):</p><input name="when" type="text">
<p>Positions (ONE per line)</p><textarea name="positions" form="newevent" rows="10" cols="50"></textarea><br>
<input value="Add Event" type="submit">
</form>
/* PHP script on insertevent.php */
<?php
$link = mysqli_connect("localhost", "root", "xxx", "xxx");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$ename = mysqli_real_escape_string($link, $_POST['ename']);
$id = mysqli_real_escape_string($link, $_POST['id']);
$imgsrc = mysqli_real_escape_string($link, $_POST['imgsrc']);
$when = mysqli_real_escape_string($link, $_POST['when']);
$descr = mysqli_real_escape_string($link, $_POST['descr']);
$positions = mysqli_real_escape_string($link, $_POST['positions']);
// attempt insert query execution
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
Don't use back-ticks for binding variables to your query, use single ticks instead. You can use back-ticks for the table and column name:
INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`)
VALUES ('$ename', '$id', '$imgsrc', '$when', '$descr', '$positions')
WHEN is also a reserved word, so better change its name.
And since you're using mysqli_* API already, check prepared statement
You are using an SQL reserved word as a column name.
$sql = "INSERT INTO events (ename, id, imgsrc, when, descr, positions) VALUES (`$ename`, $id , `$imgsrc`, `$when`, `$descr`, `$positions`)";
You really shouldn't, but if you want to get away with this, surround your table/column names with back ticks ```, like this:
$sql = "INSERT INTO `events` (`ename`, `id`, `imgsrc`, `when`, `descr`, `positions`) VALUES ('$ename', '$id' , '$imgsrc', '$when', '$descr', '$positions')";
I've removed the back ticks you put around your values because, well, they shouldn't be there.
Please learn and use MySQLi prepared statements. They'll help.
I'm trying to find a person in my table and update their score. This is the code I have right now. For some reason it's not working. Instead of changing the person's score, it will just make a new row with the same name of the person.
$name = $_POST["strtolower(name)"];
$team = $_POST["team"];
$num = $_POST["number"];
$goals = $_POST["goals"];
if($query = mysqli_query("SELECT goals FROM goalscorers WHERE name=$name ", $db)){
while($row = mysqli_fetch_assoc($query)){
$origgoals = $row['goals'];
$newgoals = (int)$origgoals + (int)$goals;
mysqli_query($db, "UPDATE goalscorers SET goals=$newgoals WHERE name=$name ");
echo "<h1>Thank you for submitting your details! <br /> Add another</h1>";
}
mysqli_free_result($query);
}
else {
$query = "INSERT INTO goalscorers (name, team, num, goals) VALUES ('$name','$team','$num','$goals') ";
$result = mysqli_query($query, $db);
if (mysqli_error()) { print "Database ERROR: " . mysql_error(); }
echo "<h1>Thank you for submitting your details! <br /> Add another</h1>";
}
I'm very new to both PHP and MySQL so it's probably a basic mistake.
Also, I already am connected to the database.
Your immediate problem is that you don't have quotes around string values in your sql queries. Change
"SELECT goals FROM goalscorers WHERE name=$name "
to
"SELECT goals FROM goalscorers WHERE name = '$name'"
^ ^
and
"UPDATE goalscorers SET goals=$newgoals WHERE name=$name "
to
"UPDATE goalscorers SET goals=$newgoals WHERE name = '$name'"
^ ^
On a side note: learn and use prepared statements. Your code is vulnerable to sql injections.
UPDATE1: You can drastically simplify your code with INSERT ... ON DUPLICATE KEY UPDATE. In order for it to work properly you have to have a UNIQUE (PRIMARY KEY) index on name column.
Your insert statement then should look like
INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)
Here is SQLFiddle demo
UPDATE2: Now your code with INSERT ... ON DUPLICATE KEY UPDATE and prepared statement can look like this
$name = $_POST['name'];
$team = $_POST['team'];
$num = $_POST['number'];
$goals = $_POST['goals'];
/* connect to the database*/
$db = new mysqli('localhost', 'user', 'userpwd', 'test');
/* check connection */
if ($db->connect_errno) {
die('Connection failed: ' .$db->connect_error);
}
$sql = 'INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)';
/* create a prepared statement */
if ($stmt = $db->prepare($sql)) {
/* bind parameters for markers */
$stmt->bind_param("ssii", $name, $team, $num, $goals);
/* execute query */
if ($stmt->execute()) {
echo '<h1>Thank you for submitting your details! <br /> Add another</h1>';
} else {
die('Insert failed: ' .$db->error);
}
/* close statement */
$stmt->close();
} else {
die('Statement prepare failed: ' .$db->error);
}
I am having some trouble making a simple form to insert data into a MySQL table. I keep getting this SQL error:
"Error: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'stock ('ItemNumber', 'Stock') VALUES ('#4','3'')' at line 1"
My HTML for the form is:
<form action="database.php" method="post">
Item Number: <input type="text" name="ItemNumber">
Stock: <input type="text" name="Stock">
<input type="submit">
</form>
And the PHP is:
<?php
$con=mysqli_connect("localhost","root","root","inventory");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
try this
you should not use quotes of parameter around POST . and you should use them inside POST
$sql = "INSERT INTO `current stock` (ItemNumber, Stock)
VALUES
('".$_POST['ItemNumber']."', '".$_POST['Stock']."' )";
you should escape your variables before you insert them to mysql like that
Note that the example does not call mysqli_real_escape_string. You would only need to use mysqli_real_escape_string if you were embedding the string directly in the query, but I would advise you to never do this. Always use parameters whenever possible.
You have an extra quote and you need ticks around your table name as it contains a space.
INSERT INTO current stock ('ItemNumber', 'Stock')
VALUES
('$_POST[ItemNumber]','$_POST[Stock]'')";
should be:
INSERT INTO `current stock` (`ItemNumber`, `Stock`)
VALUES
('$_POST[ItemNumber]','$_POST[Stock]')";
FYI, you also wide open to SQL injections
?php
$conn=new mysqli("localhost","root","","inventory")
or die("not connected".mysqli_connect_error());
if(isset($_POST['submit']{
$ItemNumber=$_POST['ItemNumber'];
$Stock=$_POST['Stock'];
$sql="insert into current stock(ItemNumber,Stock) values('$ItemNumber','$Stock')";
$query=mysqli_query($conn,$sql);
if($query){
echo"1 row inserted";
}else{
echo mysqli_error($conn);
}
}
?>
Please learn to use parameter binding. You are creating code with security vulnerabilities.
Here's how to do your code in mysqli:
$sql = "INSERT INTO current stock (ItemNumber, Stock) VALUES (?, ?)";
if (!($stmt = mysqli_prepare($con, $sql))) {
die('Error: ' . mysqli_error($con));
}
if (!mysqli_stmt_bind_param($stmt, "ii", $_POST[ItemNumber], $_POST[Stock])) {
die('Error: ' . mysqli_stmt_error($stmt));
}
if (!mysqli_stmt_execute($stmt)) {
die('Error: ' . mysqli_stmt_error($stmt));
}
It's easier to use bound parameters than to get all confused with quotes-within-quotes.
<form action="database.php" method="post">
Item Number: <input type="text" name="ItemNumber">
Stock: <input type="text" name="Stock">
<input type="submit" name="submit">
</form>`