Mysql inserts blank field from php script, but not in phpmyadmin? - php

I inserted data through the phpmyadmin into my table. It shows me the query it uses so I copied and pasted it into my php code.
My Php code is suppose to be submitting a form and I am trying to get $_POST('name') into the query.When I run the code it fills everything out but the version_name field where name goes.
Funny thing is im using the same MYSQL query that inserts it correctly on the phpmyadmin.
I have moved on to trying a random name not the POST to see if it submits but i keep getting a blank... any suggestions?
$sql = "INSERT INTO `Prototype`.`Version` ('version_id', `version_name`, `version_status`, `created_date`, `created_by`) VALUES ('','A', 'A', CURRENT_TIMESTAMP, NULL);";
this is the Insert part, and I have also tried removing the version_id since it is autoincramented but no help.
the first row is what the result looks like when submitted from my php. the second row is when I insert it right from phpmyadmin.
Any help getting version_name to be submitted from my php would be wonderful!
edit----
Heres my php code
<?php
// Retrieve form data
$name = $_POST['name'];
if (!$name) {
echo "save_failed";
return;
}
$db = array(
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'Prototype',
);
$link = #mysql_connect($db['host'], $db['login'], $db['password']);
if (!$link) {
echo "save_failed";
return;
}
mysql_select_db($db['database']);
// Clean variables before performing insert
$clean_name = mysql_real_escape_string($name);
// Perform insert
$sql = "INSERT INTO `Prototype`.`Version` (`version_name`, `version_status`, `created_date`, `created_by`) VALUES ( 'A', 'A', CURRENT_TIMESTAMP, NULL);";
if (#mysql_query($sql, $link)) {
echo "success";
#mysql_close($link);
return;
} else {
echo "save_failed";
#mysql_close($link);
return;
}
?>

firs thing first $_POST('name'); is nothing $_POST['name']; is right. Now answer to your question use following query.
$sql = "INSERT INTO `Prototype`.`Version` (`version_name`, `version_status`, `created_date`, `created_by`) VALUES ('A', 'A', CURRENT_TIMESTAMP, NULL)";
I have also checked it on my own table made from structure provided by you.
it's query is given below.
CREATE TABLE `proto` (  `version_id` int(3) NOT NULL AUTO_INCREMENT,  `version_name` varchar(45) NOT NULL,  `version_status` varchar(45) NOT NULL,  `created_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,  `created_by` varchar(45) DEFAULT NULL,  PRIMARY KEY (`version_id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
Below code is for you to submit it via php.
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host=".HOST.";dbname=".DBNAME.";charset=utf8", USERNAME, PASSWORD, $options);
$query = $db->prepare("INSERT INTO `Prototype`.`Version`
(`version_name`,
`version_status`,
`created_date`,
`created_by`)
VALUES
('A',
'A',
CURRENT_TIMESTAMP,
NULL)");
$result = $query->execute();
return $result ? true : false;

This many be by the by, and not an answer to your question but in Mysql 4 this would work:
An auto increment value can be
left out completely, if you state named fields
NULL
0
'' (empty string)
From Mysql 5 the last one will not work.
It was an undocumented feature of Mysql 4 which was removed for Mysql 5.

It was an error with the server. I deleted the database and started from scratch and it solved the issue. Almost went as far as uninstalling and reinstalling xampp.

Related

PDO not inserting into database but has correct values

I am trying to create a basic blog and I've followed the syntax completely of a previous project to insert into a mysql database but this will not add. I echo'd the values to see if it is passing it correctly and it is but when I check my database nothing is added. IS there something wrong that anyone can see with my code? Thank you in advance to anyone who answers regardless if you are able to help or not.
edit: I also checked my database and it is working correctly and is as named, also connect.php works for my login so since the information is the same it should work here.
edit2: Database table is as follows
postid int(10) auto_increment
title text
author text
date date
content text
tag1 text
tag2 text
<?php
// Make sure the user is logged in
session_name('blog');
session_start();
if (empty($_SESSION['username']))
{
header("Location: loginhome.php");
exit;
}
// Connect to the database and add a message
include("connect.php");
$one = $_POST['title'];
$two = $_POST['author'];
$three = $_POST['content'];
$four = $_POST['cat1'];
$five = $_POST['cat2'];
echo $two;
$add_message_query = $db->prepare("
INSERT INTO `blogposts`
(`title`, `author`, `date`, `content`, `tag1`, `tag2`)
VALUES
(:title, :author, CURRENT_TIMESTAMP, :content, :cat1, :cat2)
");
$add_message_query->execute(
array(
':author' => $one,
':title' => $two,
':content' => $three,
':cat1' => $four,
':cat2' => $five
)
);
//go to home to show new post
//header("Location: home.php");
?>
Please, use $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); for a better error handling.
http://www.php.net/manual/en/pdo.setattribute.php

Issues with when writing to database

I'm unable to write to my database while using this script that I whipped up earlier.
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Data sent from form, then posted to "admin" table in database
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$author = mysql_real_escape_string($_POST['author']);
$image = mysql_real_escape_string($_POST['image']);
$category = mysql_real_escape_string($_POST['category']);
$sql = "INSERT INTO admin(name,description,author,image,category) VALUES('$name','$description','$author','$image','$category');";
$result = mysql_query($sql);
header("Location: video.php?file=' . $filename . '");
}
?>
And here's my SQL:
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) UNIQUE,
description VARCHAR(50) UNIQUE,
author VARCHAR(50) UNIQUE,
image VARCHAR(50) UNIQUE,
category VARCHAR(50) UNIQUE
);
Everything is submitted with POST via an HTML form. I'm not really sure what I'm doing wrong, so that why I'm wondering what you guys think. Any thoughts?
$result = mysql_query($sql) is not valid (no connection specified).
It needs to be $result = mysql_query($sql, [CONNECTION]);
There may be other issues, but that's an obvious one.
Follow these steps:
Open a MySQL connection (if not omitted in the snippet)
Check your MySQL statement by using var_dump($sql)
Check for the return value of mysql_query(), should be true if the INSERT statement succeeded.
Check for the number of rows affected by the INSERT statement: mysql_affected_rows()
Note:
I'm pretty sure that your INSERT statement fails because all your columns are defined as UNIQUE. As soon as you already have an author with the same name the statement fails!
$auhtor=mysql_real_escape_string($_POST['author']);
The Author variable is spelled wrong.

mysql update query (containing 'where' syntax) not working

I have a mysql table like this (sql):
CREATE TABLE IF NOT EXISTS silver_and_pgm (
_metal_name varchar(30) NOT NULL,
_bid varchar(30) NOT NULL,
_change varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table silver_and_pgm
INSERT INTO silver_and_pgm (_metal_name, _bid, _change) VALUES
('Silver\r\n', '555', '-0.22\r\n'),
('Platinum\r\n', '555', '-9.00\r\n'),
('Palladium\r\n', '555', '0.00\r\n'),
('Rhodium\r\n', '555', '0.00\r\n');
and i am using the following code to update a row which contains metal_name as Silver
<?php
$username = "root";
$password = "1234";
$database = "kitco";
$con=mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$bid = '101010';
$metal_name = 'Silver';
$query = "update silver_and_pgm set _bid='$bid' where _metal_name='$metal_name'";
//$query2 = "update silver_and_pgm set _bid='444'";;
echo $query."<br>";
$result = mysql_query($query);
if(!$result)echo "error";
?>
but $query doesn't work . it works fine if I use $query2 . If I use the same query directly in SQL of phpmyadmin result is same.
what is the problem with $query . I think its correct.
Would anybody please find the bug ??
It looks like you have a line break in your _metal_name in the database, the SQL query says Silver\r\n.

What would be the correct check syntax for these strings?

I am writting a script that checks a folder K:/Comics and inserts each name + number into a database, table name = comics. Now what i would like to do would be to check to see if this comic already exists before we run the insert queries.
Table Structure:
CREATE TABLE IF NOT EXISTS `comics` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`issue` varchar(4) DEFAULT NULL,
`bio` longtext NOT NULL,
`pages` int(10) NOT NULL,
`size` varchar(100) NOT NULL,
`price` varchar(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
Code:
<?php
$main_folder = 'K:/Comics/'; // should be K:\Comics\ but I changed it because of the highlighting issue
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
$values[] = "('".mysql_real_escape_string($pair[0])."', '".((int) $pair[1])."')";
}
$query = 'INSERT IGNORE INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>
What I thought would work but doesn't (still adds comics to the db that are already there):
$query = 'INSERT IGNORE INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
What did I forget?!? The documentation said just to add IGNORE in there and it would work...
<?php
$main_folder = 'K:/Comics/';
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
// clean the values to protect against SQL injection
$pair = array(
mysql_real_escape_string($pair[0]),
mysql_real_escape_string($pair[1])
);
// add it to the values array, for insert
$values[] = "('".$pair[0]."', '".$pair[1]."')";
}
$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values).' '.
'ON DUPLICATE KEY UPDATE `issue` = VALUES(`issue`)';
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>
mysql_query() returns a result resource, not an integer or set of values or anything else. Try changing
if ($check_query == '0'){
to
if (mysql_num_rows($check_query) == 0){
However, I would probably just use:
INSERT IGNORE INTO ...
Since it probably doesn't matter. Check out the MySQL Insert Syntax for more info.
doesn't work is not too informative.
Use mysql_num_rows instead of == '0', it's really meaningless
There are no surrounding quotes around the $values.
Wrap the values with parentheses
I would place a combined unique index on the name and issue columns of the table to enforce the combination of these values to be distinct within the table.
You could then do the following and not worry about double records:
$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values).'
ON DUPLICATE KEY UPDATE id=id'; //makes sure you don't get an error
You could also use the INSERT IGNORE statement (as stated by #Dereleased) to avoid inserts of duplicates (in the before specified unique index).
Also see the documentation for the ON DUPLICATE KEY UPDATE statement, it might be helpfull in situations where you want to update the record if it was found as a duplicate while inserting.
mysql_query returns a statement handle if the query succeeds, and boolean FALSE if the query fails. You'd need to do:
$check_query_result = mysql_query(...) or die(mysql_error());
if(mysql_num_rows($check_query_result) == 0) {
... comic doesn't exist ...
}
Note that a query returning no rows is NOT a failure condition. It's simply a result that happened to have no rows

Beginner PHP: I can't insert data into MYSQL database

I'm learning PHP right now and I'm trying to insert data into a MySQL database called "pumpl2" The table is set up like this.
create table product
( productid int unsigned not null auto_increment primary key,
price int(9) not null,
value int(9) not null,
description text
);
I have a form and want to insert the fields from the form in the database. Here is what the php file looks like.
<?php
// create short variable names
$price = $_POST['price'];
$value = $_POST['value'];
$description = $_POST['description'];
if (!$price || !$value || !$description) {
echo "You have not entered all the required details.<br />"
."Please go back and try again.";
exit;
}
# $db = new mysqli('localhost', 'pumpl', '********', 'pumpl2');
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "insert into pumpl2 values
('".$price."', '".$value."', '".$description."')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows." product inserted into database.";
} else {
echo "An error has occurred. The item was not added.";
}
$db->close();
?>
When I submit the form, I get an error message "An error has occurred. The item was not added."
Does anyone know what the problem is? Thank you!
This should give you more information:
echo "An error has occurred: " . $db->error();
You are trying to insert into the table called pumpl2, but the CREATE TABLE statement created a table called product.
In addition, as ZeissS noted, you have to consider the following:
CREATE TABLE product (
productid int unsigned not null auto_increment primary key,
price int(9) not null,
value int(9) not null,
description text
);
Query OK, 0 rows affected (0.09 sec)
INSERT INTO product VALUES (1, 1, 'test');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
To solve that error, you need to explicitly specify the list of the columns:
INSERT INTO product (price, value, description) VALUES (1, 1, 'test');
Query OK, 1 row affected (0.03 sec)
You only insert three columns but have four defined in your table. Thus you have to name the columns explicitly:
INSERT INTO tableName (ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'C')
$query = "insert into pumpl2.product (price, value, description) values('" .
$db->read_escape_string($price) . "', '".
$db->read_escape_string($value) . "', '" .
$db->read_escape_string($description) . "')";
$result = $db->query($query);
And an obligatory XKCD cartoon:
Your query is wrong, you didn't have the columns specified.
Try it with:
"INSERT INTO pumpl2 (price, value, description) VALUES ('".$price."', '".$value."', '".$description."')"
Besides that, do not use the $_POST values to enter them directly into the database. Search for SQL Injection on this one. Use mysql_real_escape_string on the $_POST data first, or even better use prepared statements.
It could be several reasons.
Try
echo "Errormessage: ".$db->error;
to get more details, why the Insert didn't work.
Your table is called products not pumpl2. Furthermore you should do:
insert into product (price, value, description) values ( ...

Categories