Incorrect value is inserted in database - php

I have this code:
<form action="#" method="post">
<input type="text" name="famname"/>
<input type="submit" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
if(!isset($_POST['famname'])){
echo "Please set Family Name.";
die();
}
$mysqli = new mysqli('localhost', 'root', 'marais19', 'famlink');
if($mysqli->connect_errno) {
echo "Connection Failed (".$mysqli->connect_errno.") : ".$mysqli->connect_error;
die();
}
$e = 'yes';
$stmt = $mysqli->prepare("INSERT INTO families(famname) VALUES (?)");
$stmt->bind_param('d', $e);
$stmt->execute();
}
?>
But if I type Smith into the input box it only puts 0 into the database. The SQL code is as followed:
CREATE TABLE IF NOT EXISTS `families` (
`famname` varchar(30) CHARACTER SET utf8 NOT NULL DEFAULT 'NOFAM',
KEY `famname` (`famname`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And:
INSERT INTO `families` (`famname`) VALUES
('0');
How can I make it to put Smith into the database and not 0

You are casting it to a number (actually a double) when you bind it to the query. You need to use s instead of d:
$stmt->bind_param('d', $e);
should be
$stmt->bind_param('s', $e);
See the manual on types:
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets

Related

Error when uploading image into phpmyadmin using PDO in php

I am trying to learn inserting image into phpmyadmin my db structer:
id int(11) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
mime VARCHAR(255),
data BLOB
my code is:
<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
$dbh = new PDO("mysql:host=localhost;dbname=mydata", "root", "123456");
if(isset($_POST['btn'])){
$name = $_FILES['myfile']['name'];
$type = $_FILES['myfile']['type'];
$data = file_get_contents($_FILES['myfile']['tmp_name']);
$stmt = $dbh->prepare("INSERT INTO myblob VALUES('',?,?,?)");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$type);
$stmt->bindParam(3,$data);
$stmt->execute();
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="myfile" />
<button name="btn">Upload</button>
</form>
my error on submit:
Uncaught PDOException: SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column `mydata`.`myblob`.`id` at row 1
Any ideas what is wrong there when trying to upload a png file?
The problem is that you're sending an empty string at the 'id' value:
$stmt = $dbh->prepare("INSERT INTO myblob VALUES('',?,?,?)");
The correct would be to tell the columns with the values to add not sending anything for the 'id' column since it's is an auto increment
$stmt = $dbh->prepare(INSERT INTO myBlob(name, type, data) VALUES(:name, :type, :data)
$stmt->bindParam('name',$name);
$stmt->bindParam('type',$type);
$stmt->bindParam('data',$data);

Error adding column: You have an error in your SQL syntax;

Here is my initial createScheme.php
<html>
<body>
<form action="tableData.php" method="post">
Scheme Name: <input type="text" name="scheme"><br><br>
No of Members: <input type="text" name="memberCount"><br><br>
No. of Months: <input type="text" name="monthCount"><br><br>
EMI Amount: <input type="text" name="amount"><br><br>
Start Date:<input type="text" name="sDate"><br><br>
<!--E-mail: <input type="text" name="email"><br>-->
<input type="submit">
</form>
</body>
</html>
And here is my tableData.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gold";
$table = $_POST['scheme'];
$member = $_POST['memberCount'];
$month = $_POST['monthCount'];
$amount = $_POST['amount'];
$ldate= $_POST['sDate'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE " .$table." (
book_no VARCHAR(10) NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
contact_no VARCHAR(15) NOT NULL,
amount DECIMAL(20,3),
month VARCHAR(10) NOT NULL)";
if (mysqli_query($conn, $sql)) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
$i = 1;
while ($i <= $month)
{
$zdate = date('Y/m/d', strtotime( "+".$i." month", strtotime($ldate)))."<br>";
$column = $zdate;
echo $column."<br>";
$sql="ALTER TABLE ".$table." ADD ".$column." VARCHAR(55)";
$conn->query($sql);
$i++;
}
if (mysqli_query($conn, $sql)) {
echo "Table altered successfully";
} else {
echo "Error adding column: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
But upon execution I get this error :
> Error adding column: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '2016/12/08
VARCHAR(55)' at line 1
Note: I'm trying to create a database for a scheme management. Which involves customer details and date as column name, incremented one month from given date.
Input date is 2016/07/08
Edit: I understand problems might occur with using / in column name so I did
$column= str_replace("/", "_", $zdate);
My test echo column statement prints all dates with / replaced with _. I still have the same error.
I think name isn't the issue here.
Edit2:I'm positive the issue isn't with date format just replaced / with m, so the date now is 2016m07m08 still the same error!.
Please help me solve this, thank you
Finally solved. Knew it had to be a silly mistake. Knowing how to use quotes in sql queries can save you a lot of hassle.
this helped
Here's what I did,
replacing " with back ticks ` for cumnn variable
$sql="ALTER TABLE ".$table." ADD `$cumnn`VARCHAR(100) NOT NULL ";
I had the same problem I think MySQL no longer allows us to omit grave accents (Alt Gr + 7 key on a french keyboard).
alter table personnages
add column force tinyint unsigned not null default 20 after nom; # This doesn't work anymore
alter table `personnages`
add column `force` tinyint unsigned not null default 20 after `nom`; # This works

Update as NULL Mysql

<form action="hi.php" method="post">
<input type="text" name="id" />
<input type="hidden" name="name" value="name" />
</form>
I send this input with no value. I want to update id column as NULL.
$id = $_POST['id'];
$name = $_POST['name'];
$mysqli->query("UPDATE table SET id=$id WHERE name='$name');
However that updates it as empty not NULL. How I can insert NULL in $id?
If I send a value with <input name="id">, it updates it correctly. However if I send it empty, column becomes empty, I want it as NULL.
When using prepared statements and parameters, a NULL value in one of the parameters will also be treated as NULL by the MySQL server.
HTTP parameters are transported as strings. If no value has been given for an input control, the value for the key/value-pair will be an empty string (!=NULL). But you can still have somethig like if(emptystring) use NULL in your script.
e.g.
<?php
// only for this example; otherwise leave _POST alone....
$_POST['id'] = 1;
$_POST['name'] = '';
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_errno) {
trigger_error( sprintf('mysqli connect error (%d) %s', $mysqli->connect_errno, $mysqli->connect_error), E_USER_ERROR);
die;
}
mysqli_report(MYSQLI_REPORT_STRICT|MYSQLI_REPORT_ALL); // that's all the "error handling" for this example....
setup($mysqli);
// even if the user didn't fill in any value, the parameters should be in the request
// as empty strings
if ( !isset($_POST['name'], $_POST['id']) ) {
echo 'missing POST paramete';
}
else {
// <-- maybe some plausiblity checks here anyway; e.g. some assumptions about the id you can test, leaving it out as optional for now --->
// decision point: applying trim() to _POST[name] and _then_ consider it NULL or not - you might disagree about the specifics, just an example.
$name = trim($_POST['name']);
if ( 0===strlen($name) ) {
$name = NULL;
}
// <-- actually it would suffice to establish the databse connection here....
$stmt = $mysqli->prepare('UPDATE soFoo set name=? WHERE id=?');
$stmt->bind_param('ss', $name, $_POST['id']);
$stmt->execute();
printTable($mysqli);
}
function printTable($mysqli) {
$result = $mysqli->query('SELECT * FROM soFoo ORDER BY id');
foreach( $result as $row ) {
var_export($row); echo "\r\n";
}
}
function setup($mysqli) {
$mysqli->query('CREATE TEMPORARY TABLE soFoo (id int, name varchar(32), primary key(id))');
$mysqli->query("INSERT INTO soFoo (id,name) VALUES(1,'oldname1'),(2,'oldname2')");
}
prints
array (
'id' => '1',
'name' => NULL,
)
array (
'id' => '2',
'name' => 'oldname2',
)
I suggest you use PDO, and not mysql() but this will give you the idea:
$id = $_POST['id'];
if($id==''){
$id='NULL';
}
else{
$id = mysql_real_escape_string($id);
}
$qr = 'Update table SET id='.$id;
mysql_query($qr);

PHP Can't enter data into database table

I am trying to enter the data that I get from the two variables stuname and book in the table's username and book columns !! I only want to enter data into those two columns since the id column is auto increment and the date is auto updated with time stamp!!! Each time I run my code I enter my data into the two text fields and when I press submit I get this message!!
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\assignment.php on line 35
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\assignment.php on line 36
Here is my Code:
<?php
$servername = "localhost";
$Username = "root";
$Password = "admin";
$Dbname = "nfc";
$conn = mysqli_connect($servername, $Username, $Password, $Dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Connected successfully";
if(isset($_POST["stuname"])&&($_POST["book"]))
{
$stuname = $_POST["stuname"];
$book =$_POST["bookname"];
$sql = "INSERT INTO library (id, username, book, date)
VALUES ('', '$stuname', '$book','')";
mysqli_select_db($conn, 'nfc') or die(mysqli_error($con));
$retval = mysqli_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Success";
}
echo " to stuname ". $stuname;
echo " to book ". $book;
}
?>
<form id="form1" name="form1" method="post" action="#">
<p>
<label for="1">student name</label>
<input type="text" name="stuname" id="1" />
</p>
<p>
<label for="12">book name</label>
<input type="text" name="bookname" id="12" />
</p>
<input name="submit" type="submit" value="Submit" />
</form>
In the mysqli_query you should put the conn first and then the query itself
$retval = mysqli_query( $conn, $sql );
The first problem was solved by #Ghost in the comments.
Now on to the rest of the problems:
1. Your database design is faulty
This should have failed immediately because you are inserting an empty value for id. id should be a primary key and therefore should be unique. An auto-increment doesn't work if you insert an empty value.
2. Your insert statement is faulty
You should exclude an auto-increment column in the INSERT statement and should not use an empty value for date. If date is a timestamp, you should either use NULL if the time is supposed to be empty or use NOW() to use the current timestamp.
3. You shouldn't be using insert on this page according to your comments.
You should be using UPDATE or REPLACE instead of INSERT if you are trying to update the existing row but you should be using the primary key to signify which row you are replacing. Right now, it looks like you don't have a primary key, so refer to my 1st point.
4. Security concerns: Your query is subject to SQL injections.
You use user input ($_POST) directly in a query. Any malicious user can take advantage of this and extract, delete, or manipulate data in your database. You should be using prepared statements, or at the very least escape functions.

Why is the server rejecting my PDO query?

I've been trying to write a simple search and display site with a drop down menu, I've tried using mysqli and PDO and I'm not getting the results. I've just checked the server log in cpanel and found that the access has been denied to the results page. The access must be all right for the drop down page as it is populating the drop down list. I can't see why it is being stopped. The server is running PHP 5.3.27 and MYSQL 5.5.36.
This is the drop down.
<form action="search3.php" method="post" >
<?php
$mysqli = new mysqli('localhost','user','password','engraved_stamps');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$query = "SELECT DISTINCT Country FROM engravers ORDER BY Country";
$result = $mysqli->query($query);
?>
<select >
<?php
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['Country']}\">";
echo $row['Country'];
echo "</option>";
}
$mysqli->close();
?>
</select>
<input type="submit" name="dropdown" />
</form>
This is the results page (action for restul) (called Search3.php)
<?php
$hostname = "localhost";
$user = "user";
$password = "password";
$connection = mysqli_connect($hostname, $user, $password,);
if(!$connection){
echo"Could not connect to server";
};
mysqli_select_db($connection,'engraved_stamps');
if(!mysqli_select_db($connection,'engraved_stamps')){
echo"could not connect to database";
};
if(isset($_POST['dropdown'])){
$Country = $_POST['dropdown'];
}else{
$Country = "none";
}
$sql= "SELECT * FROM engravers WHERE Country = :Country";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Country', $Country, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();
while ($row = $stmt->fetchObject()) {
echo $row->Country;
}
$mysqli->close();
?>
I think PDO and mysqli are different PHP extensions. You should choose only one thing to deal with your work.
e.g., you can use mysqli only, or PDO.
For more information about PDO, see: http://php.net/manual/en/pdo.construct.php
You are mixing two entirely different database extensions:
MySQL Improved Extension (aka mysqli):
$mysqli = new mysqli(...)
^^^^^^
PHP Data Objects (aka PDO):
$stmt->bindParam(':Country', $Country, PDO::PARAM_STR);
^^^
Despite your question title and tags, your code seems to use mysqli entirely. You'll just need to get rid of the PDO bits.
You're also using some undefined variables:
$stmt = $pdo->prepare($sql);
^^^^
You're apparently not getting the corresponding error messages, which suggests you haven't configured your PHP development box to do so. As soon as you do it, you'll be possibly warned of some other issues.
Sorry abas_rafiq. the comments only allow a certain number of characters.
Here is the structure:
CREATE TABLE IF NOT EXISTS engravers (
Key int(10) NOT NULL AUTO_INCREMENT,
StampImages text NOT NULL,
Images text NOT NULL,
Country text NOT NULL,
Year int(4) NOT NULL,
Description text NOT NULL,
SGNumber text NOT NULL,
ScottNumber text NOT NULL,
Engraver1Surname text NOT NULL,
Engraver1OtherNames text NOT NULL,
Engraver2Surname text NOT NULL,
Engraver2OtherNames text NOT NULL,
Engraver3Surname text NOT NULL,
Engraver3OtherNames text NOT NULL,
Designer1Surname text NOT NULL,
Designer1OtherNames text NOT NULL,
Designer2Surname text NOT NULL,
Designer2OtherNames text NOT NULL,
Printer text NOT NULL,
Notes text NOT NULL,
PRIMARY KEY (Key),
UNIQUE KEY Key (Key)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=91 ;
They were not all "Not Null" when I set it up but I see they are now.
<?php
try {
//here add user and password and database please be sure u have used correct one
$dbh = new PDO("mysql:host=localhost;dbname=engraved_stamps",'root','');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
$STM = $dbh->prepare("SELECT * FROM engravers WHERE Country = :Country");
if(isset($_POST['dropdown'])){
$Country = $_POST['dropdown'];
}else{
$Country = "name";//here you can assing % too for value of any if u need tell me to recode, NOTE here now the value u have assign is (name) is the record value on ur engravers table for column of Country.
}
$STM->bindParam(':Country', $Country, PDO::PARAM_STR);
$STM->execute();
$row= $STM->fetchAll();
if(count($row)){
foreach($row as $data){
echo $data['Country'] . "<br />";// here country is the column of ur table u can echo other columns too
}
}else {
echo 'no row found';
}
?>

Categories