<?php
require "config.php";
/*
CREATE TABLE `addnews` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`auther` VARCHAR( 255 ) NOT NULL ,
`title` VARCHAR( 255 ) NOT NULL ,
`content` LONGTEXT NOT NULL
) ENGINE = MYISAM ;
*/
$a = $_POST['author'];
$t = $_POST['title'];
$c = $_POST['content'];
if(isset($_POST["add"]) and $_POST["add"] == "news"){
$insert = mysql_query('INSERT INTO addnews
(author,title,content)
VALUES
("$a","$t","$c")') or die("error");
if (isset($insert )){
echo "<h3>Done</h3>";
}
};
echo "
<form action='".$_SERVER['PHP_SELF']."' method='post'>
Author : <input type='text' name='author' /><br>
Title : <input type='text' name='title' /><br>
Content : <textarea name='content'></textarea>
<input type='submit' value='Add news' />
<input type='hidden' name='add' value='news' />
</form>
";
mysql_close($connectdb);
?>
i am getting error from this statment i think
if(isset($_POST["add"]) and $_POST["add"] == "news"){
$insert = mysql_query('INSERT INTO addnews
(author,title,content)
VALUES
("$a","$t","$c")') or die("error happend while trying to add information to database");
if (isset($insert )){
echo "<h3>Done</h3>";
}
};
output is : error happend while trying to add information to database
and no problem with config.php file (the file that connect to database)
i am using phpmyadmin
strings in sql are surrounded by ' (single quote) , not by " (double quote)
strings in php will act two ways
those in ' (single quote) will write literally as tyou typed them ($a stays $a - not $a value)
those in " (double quote) will interpret values inside - so $a will be substituted with $a's value
when failing DB operation - it is usually useful to see what was wrong - use mysql_error for that
Use && instead of the actual word and:
if(isset($_POST["add"]) && $_POST["add"] == "news"){
$insert = mysql_query("INSERT INTO addnews
(author,title,content)
VALUES
('$a','$t','$c')") or die("error happend while trying to add information to database");
if (isset($insert )){
echo "<h3>Done</h3>";
}
};
Here you go try this one
if(isset($_POST["add"]) and $_POST["add"] == "news"){
$insert = mysql_query('INSERT INTO addnews
(author,title,content)
VALUES
("'. $a .'","'. $t .'","'. $c .'")') or die("error happend while trying to add information to database");
if (isset($insert )){
echo "<h3>Done</h3>";
}
};
used "'. $a .'" instead "$a".
I think the query statement is wrong,
Double quotes inside the single quotes is not valid in php.
So you will change the quotes in query like below code,
$insert = mysql_query("INSERT INTO addnews
(author,title,content)
VALUES
('$a','$t','$c')") or die("error");
try this..:-)
Please do the correction in your code like as follow:
$insert = mysql_query("INSERT INTO addnews
(author,title,content)
VALUES
('$a','$t','$c')") or die(mysql_error($link));//Where $link mysql resource object
You will get the answer why Mysql not inserting your data.
Related
I am going to start this off by saying -- yes I know there are other links similar to this and topics similar to this and I have read all of them and incorporated them into my code. However, I cannot figure it out and have tried everything I can.
Basically my goal is to take a users input from an html form called socialmedia.html:
<html>
<body>
<h1> Pulse submission page </h1><br>
<form action="action.php" method="post">
Title: <input type="text" name="posttitle"><br><br>
Content: <input type="text" name="content"><br><br>
<input type="submit">
</form>
</body>
</html>
and then send it to a php file called action.php:
<?php
$mysqli = new mysqli("DB HOST IP", "USER", "PASS", "DB NAME");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$posttitle = $_POST["posttitle"];
$content = $_POST["content"];
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
echo 'post added to database';
}
if($sql){
echo 'success';
}
else{
echo 'failure';
}
$sql = "SELECT * FROM `posts`";
$res = $mysqli->query($sql);
if($res->num_rows > 0){
while($row = $res->fetch_assoc()){
echo "ID". $row["id"]. "<br/>";
echo "Title". $row["posttitle"]. "<br/>";
echo "Content". $row["content"]. "<br/>";
}
}
else
{
echo "No Record Found!";
}
?>
This file is SUPPOSED to insert the user's form values into the table posts:
this is the table posts
and then print the whole table to a webpage-- action.php this is what it prints (with the error checks and all):
this is the page, I blurred out the IP
NOTE: I manually inserted the first title and content to see if the code could read from the database (which it can)
honestly, I do not know where I went wrong and I have die extensive research at this point. It's probably going to end up being a syntax error and I'm gonna be kicking myself. It could have something to do with me using a Godaddy server and the phpMyAdmin and database being through there. I am using mysqli instead of PDO because PLESK and Godaddy do not support PDO yet.
<input type="submit" name="submit" /> try with this
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle', '$content')";
$save = $mysqli->query($sql);
if($save)
echo 'success';
else
echo 'failure';
}
several things to get you started
1) missing quote after PASS
mysqli("DB HOST IP", "USER", "PASS, "DB NAME");
2) you are not executing your INSERT query, missing $mysqli->query($sql);
if(isset($_POST['submit'])){
$sql = "INSERT INTO `posts` (posttitle, content) VALUES ('$posttitle',
'$content')";
echo 'post added to database';
}
You have to give name of the submit butto as
input type="submit" name="submit"
"INSERT INTO posts (posttitle, content) VALUES ('$posttitle', '$content')"
This is a code for inserting the barcode into a database but if the same barcode exists in the database, I don't need this to be inserted same again, so I coded like this but still, the same barcode is inserting in my database. What the error in this code?
I am using mysqli and Bootstrap to show the errors in the page, the page is executed from another page called product.php via ajax and it is showing in another page called showuser.php as it gets updated in a table which should give the output
<?php
include('conn.php');
if(isset($_POST['add'])){
$proname=$_POST['product'];
$bar=$_POST['barcode'];
$war=$_POST['warranty'];
$gar=$_POST['guarranty'];
$amount=$_POST['amount'];
$id = $_POST['cusid'];
$date = $_POST['date'];
$check = "SELECT * FROM warranty_update WHERE battery_serial = '$bar'";
$rs = mysqli_query($con,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
?>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<h3 align="center"><i class=" glyphicon glyphicon-warning-sign"></i><br>
<br>
Sorry Barcode Already Been Inserted !<br><br>
Please Go Back</h3>
<?php } else {
$datesplit = explode("-",$date);
$warranty = $datesplit[0];
$guarante = $datesplit[0];
$day = $datesplit[1];
$month = $datesplit[2];
$fdate = strtotime($date);
$Gm=strtotime("+$gar Months",$fdate);
$wm=strtotime("+$war Months",$Gm);
$m1=date("Y-m-d", $Gm) ;
$m2 =date("Y-m-d", $wm) ;
$today = date("Y/m/d");
$expiry_warranty = $m2;
$expiry_guarante = $m1;
//mysql_query("INSERT INTO `cus_reg`(`reg_id`, `name`, `mobile`, `battery_serial`, `model`, `date`, `reg_by`, `warranty_expiry`, `waranty_span`,`guarantee_expiry`, `g_span`) VALUES (NULL,'$name','$mobile','$battery_serial','$vehicle_num','$date','$regby','$expiry_warranty', '$wmonth', '$expiry_guarante', '$gmonth')")==true or die(mysql_error);
//mysql_query("INSERT INTO `warranty_update`(`wa_id`, `cus_reg_id`, `new_barcode`, `date`) VALUES (NULL,LAST_INSERT_ID(),'$battery_serial','$today')");
mysqli_query($conn,"INSERT INTO `warranty_update`(`wa_id`, `reg_id`, `battery_serial`, `model`, `date`, `warranty_expiry`, `waranty_span`, `guarantee_expiry`, `g_span`, `amount`) VALUES (NULL,'$id','$bar','$proname','$today','$expiry_warranty','$war','$expiry_guarante','$gar','$amount')");
mysqli_query($conn,"INSERT INTO `replacements`(`r_id`, `reg_id`, `wa_id`, `new_barcode`, `date`) VALUES ('NULL','$id',LAST_INSERT_ID(),'$bar','$today')");
?>
<!--header("refresh:1;url=home.php");-->
<h3 align="center"><i class=" glyphicon glyphicon-warning-sign"></i><br>
<br>
Data Successfully Inserted !
<?php }
}
?>
Not entirely sure, but you should check you array like this for entries:
if (count($data) > 0)
The best way to do this is defining a unique constraint on barcode via SQL.
Anyway I think that you are valuating the condition in an erroneous mode.
$data is an array, so you should check his size with: sizeof.
so: if(sizeof($data) > 1) { .... }
Hi guys I'm having trouble with my PHP code. Unable to update the database when I submit the form. I'm trying to update the new price.
Here's my PHP code:
<?php
if(isset($_POST['update']))
{
# $db = new mysqli('localhost','XXXX','XXXX','XXXX');
if(! $db )
{
die('Could not connect: ' . mysqli_error());
}
$price = $_POST['price'];
$sql = "UPDATE bookprice ".
"SET price = price " ;
mysqli_select_db('books');
$retval = mysqli_query( $sql, $db );
if(! $retval )
{
die('Could not update data: ' . mysqli_error());
}
echo "Updated Price successfully\n";
mysqli_close($db);
}
else
{
?>
Form code:
<form method="post">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input name="update" type="submit" id="update" value="Update Price">
<input name="price" type="text" id="price">
</td>
</tr>
</table>
</form>
Still in the process of grasping PHP. Any form of help is greatly appreciated!
You're not using the $price variable to set the price column to.
Use "SET price = $price " ;
or inside quotes "SET price = '$price' " ;
What you're doing right now is "set the price column equals price column" instead of the intended value taken from the POST variable $price. More on this at the end of my answer under Footnotes.
Another thing:
$retval = mysqli_query( $sql, $db );
you need to reverse the query and DB connection:
$retval = mysqli_query( $db, $sql );
In mysqli_, the connection comes first, then the query's variable.
Plus, use:
$db = new mysqli('localhost','XXXX','XXXX','books');
You're using all four parameters in your DB connection, so you can drop:
mysqli_select_db('books');
since you're not doing anything with it, and simply add books as the DB's parameter.
Using the fourth parameter with the DB's name, is the same as using mysqli_select_db with the DB's name and connection variable, which is something you are not using.
Read the manual http://php.net/manual/en/mysqli.select-db.php
You also have a missing closing brace in
else
{
?>
if you don't have anything after that, do:
else
{
echo "Fail";
}
?>
Footnotes:
If your price contains a dollar sign, or a dot or mix of those, or something else that SQL does not agree with (which am under the impression it could), you will need to wrap it in quotes:
$sql = "UPDATE bookprice SET price = '$price' " ;
or
$sql = "UPDATE bookprice SET price = '".$price."' " ;
If your column is an int type, then you can use
$sql = "UPDATE bookprice " . "SET price = ".$price;
remove #
$db = new mysqli('localhost','XXXX','XXXX','XXXX');
and update the query
$sql = "UPDATE bookprice ".
"SET price = ".$price ;
Give this a try:
<?php
if($_POST['update']){
$db = new mysqli('localhost','XXXX','XXXX','XXXX'); // remove '#'
if(!$db){
die('Could not connect: ' . mysqli_error($db)); // Needs the database connection
}
$price = $_POST['price'];
$sql = "UPDATE `bookprice` SET `price` = '$price'"; // Use the variable $price
// mysqli_select_db('books'); // This should already be set in the new mysqli();
$retval = mysqli_query($db, $sql); // Turn this around;
if(!$retval) {
die('Could not update data: ' . mysqli_error($db)); // needs the database connection
} else {
echo "Updated Price successfully\r\n"; // \r\n will always work \r or \n alone will not always work
}
mysqli_close($db);
}
else {
echo 'There was no post';
}
?>
HTML:
<form action="" method="post">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input name="update" type="submit" id="update" value="Update Price">
<input name="price" type="text" id="price">
</td>
</tr>
</table>
</form>
Links:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/mysqli.query.php
http://nl3.php.net/manual/en/mysqli.real-escape-string.php
http://php.net/manual/en/function.number-format.php (since you are working with a price this may come in handy)
You should also consider the use of mysqli_real_escape_string() so:
$price = mysqli_real_escape_string($db, $_POST['price']);
Well actually if you concat your queries with $parameter directly, it opens up a security risk
$price = $_GET["price"] (from the URL)
$price = $_POST["price"] (from the FORM Post)
UPDATE bookprice SET price = '$price'
You should try using prepared statements like
Update bookrprice set price = :price
or
Update bookrprice set price = ?
and then create a associate key value pairs to security and pass it in to your query. This is why it is not recommend to use mysql_query and rather mysqli or PDO methods.
then your would pair the above statement by
execute(array(":price"=>$price))
or
execute(array($price))
I have a HTML form; I want to be able to set it so that if a field is empty, the field in the DB will actually be NULL and not just have the word NULL in the field. I thought that using this code would help, but it just puts the word NULL in the field.
PHP Code:
<pre>
<?php
if (isset($_POST['oc_item'])) {
$oc_item = mysql_escape_string($_POST['oc_item']);
$oc_itemdesc = (!empty($_POST['oc_itemdesc'])) ? $_POST['oc_itemdesc'] : NULL;
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES(''$oc_item','$oc_itemdesc')";
mysql_query($SQL);
if (mysql_query($sql)) {
echo '<strong><em>Your data has been submitted</em></strong><br /><br />';
} else {
echo '<p>Error adding submitted info: ' . mysql_error(). '</p>';
}
}
?></pre>
HTML Code:
<pre>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>Item Name</td>
<td><input class="forms" type="text" size="50" maxlength="50" name="oc_item" /></td>
</tr>
<tr>
<td>Item Description</td>
<td><input class="forms" type="text" size="50" maxlength="50" name="oc_itemdesc" /></td>
</tr>
</table>
<p><input type="submit" value="Submit item" /></p>
</form></pre>
I want the field to actually be NULL and not have the field contain the word NULL. Thanks in advance.
If you want to write NULL to a MySQL database, you really have to put NULL there without quotation marks.
Like this:
INSERT INTO table (column, column2) VALUES ('mystring', NULL);
It’s always a bit effort if you want to do this manually by hand, because you would have to make if-conditions for the query.
Remember: PHP null != MySQL NULL. They both do not know each other at all.
But I am still wondering, what does that all have to do with the question name? (SELECT unless)
You could write your code like this:
$oc_item = mysql_escape_string($_POST['oc_item']);
$oc_itemdesc = (isset($_POST['oc_itemdesc']) && trim($_POST['oc_itemdesc']) != '') ? "'" . mysql_escape_string($_POST['oc_itemdesc']) . "'" : 'NULL';
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('" . $oc_item . "', " . $oc_itemdesc . ")";
# sorry for adding " . all the time, but I dislike variables within strings :D
But I have to admit I do not like that much either, as it moves the duty to wrap quotation marks around MySQL strings away from the SQL-query itself.
If you printed out $sql, you'd see that it's inserting , 'NULL'.
You need to modify your code so that it inserts the work "NULL" (without '' quotes) or, better, doesn't insert that parameter at all (eliminate the entire , 'NULL' part of the string.
Try this:
$oc_itemdesc = (!empty($_POST['oc_itemdesc'])) ? "'".$_POST['oc_itemdesc']."'" : "NULL";
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('$oc_item',$oc_itemdesc)";
As it stands you are adding 'NULL' instead of NULL so it is adding the words instead of the value.
Side Note: I would be careful and properly escape/encode the $_POST['oc_itemdesc'] as someone who put an apostrophe in the description would completely throw off the insert statement. For example: I don't like this would look like this:
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('$oc_item','I don't like this')";//MYSQL Error
PPS: As it stands you are inserting TWICE:
mysql_query($SQL);//insert 1
if (mysql_query($sql)) {//insert 2
The function that I use for the MySQL data from the HTML forms.
function emptyHtmlFormToNull($arr){
foreach($arr as $key => $val){
if(empty($val) || strtolower($val) === 'null'){
$arr[$key] = null;
}
}
return $arr;
}
I have a strange thing over here. I'm trying to insert a value in my database but it's not working for some reason. I have this code:
PHP:
<input type='file' name='images[]' />
<input type="text" name="newproject_name" id="tags"/>
<input type='text' name='order[]' value='$b' />
$project = new Project();
$project->photo = $_FILES['images']['name'][$key];
$project->order = $_POST['order'][$key];
$projectnaam = $_POST['newproject_name'];
if($project->createProject($_DB)) {
echo "OK";
} else {
echo "NOT OK";
}
}
FUNCTION:
class Project {
public function createProject($db) {
$sql = "INSERT INTO tblProject (
project,
photo,
order) // If you remove this line, the function is working
VALUES(
'".$db->escape($this->project)."',
'".$db->escape($this->photo)."',
'".$db->escape($this->order)."' // If you remove this line, the function is working
)";
return $db->insert($sql);
}
}
Strange thing is, when I delete the order-lines, the function is working just fine. I really don't know what I'm doing wrong...
ORDER is a reserved word. If you use backticks around the column name you should be good:
$sql = "INSERT INTO tblProject (
`project`,
`photo`,
`order`)
VALUES(
'".$db->escape($this->project)."',
'".$db->escape($this->photo)."',
'".$db->escape($this->order)."'
)";
I suggest you change the order column name to position or display_order.