Query won't insert username into database - php

So I've got this query:
mysql_query(
"INSERT INTO wall_post (post,username,userip,date_created)
VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."'
)"
);
and I also tried to make the query this way:
mysql_query(
"INSERT INTO wall_post (post,username,userip,date_created)
VALUES(
'".checkValues($_REQUEST['value'])."',
$_SESSION['user'],
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."'
)"
);
I don't see any error message from the database when the insert fails.
It won't insert the username into the database but when I echo $_SESSION['user'] it would still show me its content, please I would appreciate some help.
The table structure is:
CREATE TABLE wall_post (
p_id int(11) NOT NULL auto_increment,
username varchar(50) NOT NULL,
post varchar(255) NOT NULL,
image varchar(50) NOT NULL,
date_created int(11) NOT NULL,
userip varchar(200) NOT NULL, PRIMARY KEY (p_id)
)
The value which contains $_SESSION['user'] is theil, it doesn't have any special character, but if I replace $_SESSION['user'] with a string like $user = "test"; it will insert the value "test" into the database

mysql_query for insert statements either returns True on success or False on error. You have to check the return value if it was successful, and if it wasn't successful get the error via mysql_error:
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
It should be easy to fix from there.

The image column is set to NOT NULL, but you are not inserting anything into it. I suspect removing the NOT NULL clause, or setting a default value for the column might fix your problem.
Additional tip. use MYSQLS NOW() for the date. Just let the database handle that bit :)

just check what the value is and make sure there are no special characters in there.
You can also try "'.mysql_real_escape_string($_SESSION['user']).'"
the problem might be special characters.
From all the comments try this
$name = isset($_REQUEST['user']) ? $_REQUEST['user'] : '';
mysql_query('INSERT INTO wall_post (post,username,userip,date_created) VALUES("'..checkValues($_REQUEST['value']).'",
"'.$name.'","'$ipAddress'","'.$timestamp.'")');

From one of your comments above, I learnt that if you echo your query, it shows as
INSERT INTO wall_post (post,username,userip,date_created)
VALUES('','theil','127.0.0.1','1309975742')
Did you do this echo just before the statement where you run the query? If not, I'd request you to please do the echo just before the call, like this:
echo "INSERT INTO wall_post (post,username,userip,date_created) VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."')";
mysql_query("INSERT INTO wall_post (post,username,userip,date_created) VALUES(
'".checkValues($_REQUEST['value'])."',
'".$_SESSION['user']."',
'".$userip."',
'".strtotime(date("Y-m-d H:i:s"))."')"
);
Your query seems to be absolute fine and should run fine. The only reason why username might not be saving into the database is that `$_SESSION['user'] is empty or does not exist.
Did you try running this echoed query - INSERT INTO wall_post (post, username, userip, date_created) VALUES('', 'theil', '127.0.0.1', '1309975742') - directly into MySQL, either on the prompt or any other client that you might be using?

Related

PHP mysqli - updating value of enum field results in empty string, but same query works when run in PHPMyAdmin

The query:
UPDATE caption_queue SET status = 'Conversion Completed' WHERE tpi_id = '3130'
As stated in the title, when I run this in PHP, the value is set to an empty string. However, when the exact same query is run directly in MySQL, it works correctly.
On top of that, I'm only getting this behavior on a single enum value: 'Conversion Completed'. When updating with other values (most of which also contain spaces), there is no problem.
Actual PHP code for those interested:
$sql = "UPDATE caption_queue SET status = 'Conversion Completed' WHERE tpi_id = '$tpi_id'";
$val = mysqli_query($link, $sql);
//$link comes from somewhere else, but we use it extensively throughout our website
Table definition:
CREATE TABLE IF NOT EXISTS `caption_queue` (
`tpi_id` int(11) NOT NULL,
`pid` int(6) DEFAULT NULL,
`conversion_began` datetime DEFAULT NULL,
`yt_caption_id` varchar(50) DEFAULT NULL,
`yt_video_id` varchar(50) DEFAULT NULL,
`status` enum('Pending Conversion','Converting','Conversion Completed','Pending Upload','Video Processing','Video Processed','Uploading Transcription','Caption Syncing','Caption Synced','Caption Downloading','Caption Ready') DEFAULT 'Pending Conversion'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
if you are using MySQLI and your database has enums you need to find the place of your value in order to update your database because it does not accept new strings!
here is an example of the column of my database configuration!
status enum('active', 'inactive', 'banned')
if you want to update these values convert the values into numbers for example active = 1, inactive = 2, banned = 3
from PHP we are able to do the following
$query = 'UPDATE '.$this->table.' SET status = :status'
$stmt = $this->conn->prepare($query);
if($this->status == 'active')
{
$finalStatus = 1;
}
if($this->status == 'inactive')
{
$finalStatus = 2;
}
if($this->status == 'banned')
{
$finalStatus = 3;
}
$stmt->bindParam(':status', $finalStatus);
$stmt->execute();
and this will save your day!
this code was used as an example to provide a full solution to this issue!
Thanks.
I think you'll find it should work if you put the column called status in back ticks.
$query="UPDATE caption_queue SET `status` = 'Conversion Completed' WHERE tpi_id = '3130'";
I found a workaround. By using strict mode:
SET SESSION sql_mode = 'STRICT_ALL_TABLES'
I'm able to update the field with no issues. Seems like some kind of issue with mysqli.

SQL Syntax Error when running through PHP but runs fine as an SQL Query

So, a snippet of my code which is resulting in an error is :
$con = mysqli_connect('localhost', 'root', '', 'notesDB');
if(isset($_POST['tableName'])) {
$tName = htmlentities($_POST['tableName']);
$firstQuery = mysqli_query($con,"INSERT into notes(Title) VALUES( '$tName'); CREATE TABLE $tName(id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, Description varchar(100), PRIMARY KEY(id));");
if($firstQuery){
header("Location: create2.php");
}
else
echo mysqli_error($con);
}
The output of this is :
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 'CREATE TABLE test1(id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, D' at line 1
Well, the funny thing is that the exact code (except the variable - I just removed the $ sign) executed perfectly in phpMyAdmin.
Also, to prove that there is nothing really wrong with the php, the query executed without any error when it was only the INSERT query (and not the CREATE query).
mysqli_query can only perform one query at a time.
Try mysqli_multi_query instead.
As an aside creating tables on the fly is usually a sign of larger design issues. Schema should be relatively static while data should be dynamic.
You are trying to run two separate queries at a time in the code, which you can't run like that. You have to run them separately like below:
$con = mysqli_connect('localhost', 'root', '', 'notesDB');
if(isset($_POST['tableName'])) {
$tName = htmlentities($_POST['tableName']);
$firstQuery = mysqli_query($con,"INSERT into notes(Title) VALUES( '$tName')");
$secondQuery = mysqli_query("CREATE TABLE '$tName' (id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, Description varchar(100), PRIMARY KEY(id));");
if($firstQuery || $secondQuery){
header("Location: create2.php");
}
else
echo mysqli_error($con);
}
Your database architecture is wrong.
You shouldn't create tables on the fly. So, you have only register whatever new entity with simple regular INSERT query. And then use this entity's id to link records from another [already existing] table.
if(isset($_POST['tableName'])) {
$stm = mysqli_prepare($con,"INSERT into notes(Title) VALUES(?)");
$stm->bind_param("s",$_POST['tableName']);
$stm->execute();
}

Check whether records exist in database

I know there are various offered solutions for this topic posted on this site, and I checked (and used) some of those solutions. Nevertheless, I can't figure out why my code below does not work, probably because I'm a starter with respect to php and sql programming ;-(
The code is supposed to add a record with 3 fields (FirstName, LastName, Age) in a table (persons), but only if the record does not already exist. Therefore a check on existing FirstName and Lastname fields is performed. But in case of existing record the condition of the if statement still seems to be true and a copy of the existing record is still inserted into the database. What do I miss?
Thanks in advance for the help.
//check whether item does not exist in database
$query ="SELECT FirstName,LastName FROM persons
WHERE FirstName='$data[1]' AND LastName='$data[2]'";
$result = mysql_query($query);
if($result && mysql_num_rows($result) > 0)
{
echo " <br> record exist";
}
else
{
$theage = (int)$data[3]; //! for conversion of integer values
$sql="INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$data[1]','$data[2]','$theage')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
You have to use {} around array values in query
$query ="SELECT FirstName,LastName FROM persons
WHERE FirstName='{$data[1]}' AND LastName='{$data[2]}'";
Also your INSERT query runs on mysqli and SELECT query runs on mysql. You have to use only 1 not both and use below code with mysqli.
$result = mysqli_query($con,$query);
if($result && mysqli_num_rows($result) > 0)
{
echo " <br> record exist";
}
May be this query will help you:
INSERT INTO persons (FirstName, LastName, Age)
SELECT * FROM (SELECT FirstName,LastName) AS tmp
WHERE NOT EXISTS (
SELECT FirstName, LastName FROM persons WHERE WHERE FirstName='$data[1]' AND LastName='$data[2]'
) LIMIT 1;
Check your connection
In first query you have used
mysql_query
then in second case at the time of insert you use
mysqli_query
From the database perspective, modify your Person table design by setting a UNIQUE KEY for the necessary fields i.e :
CREATE TABLE `Persons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_FirstName_LastName` (`FirstName`,`LastName`) USING BTREE
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
Do a normal insert, handle the duplicate error
[Err] 1062 - Duplicate entry 'jk-kenneth' for key 'unique_FirstName_LastName'

MySQL Unknown column in where clause for simple select statement

I have a very basic select statement that is causing a column unknown error. The problem with the query happens when I try to use a character instead of just numbers in the variable. Wondering if it has anything to do with Collation.
Here's what I have so far:
$titleno=$_REQUEST['title_no'];
$titleno=mysql_real_escape_string($titleno);
$titleno = utf8_decode($titleno); //tried without this before but didn't work
$query="SELECT * FROM `Titles` WHERE `title-no` = '".$titleno."'";
//tried various versions of this query - left it as single quotes as that seems to be the correct way. This only fails when a character is entered. Numbers work fine.
echo "query - <br> $query <br>";
$get_title_result=mysql_query($query) or die(mysql_error());
//here I get the unknown column name error - MySQL treats the titleno as the column name
Echo output:
SELECT * FROM `Titles` WHERE `title-no` = '1234566d'
Unknown column '1234566d' in 'where clause'
If I didn't use the 'd' in title-no, it works fine....Also, I tried a different column name that doesn't have the hyphen and still get the same behavior. The DB defines collation for title-no as latin1_swedish_ci. (This problem doesn't occur when I paste the query into mysqladmin)
Here's the table definition:
CREATE TABLE `Titles` (
`id` int(11) NOT NULL auto_increment,
`title-no` varchar(15) NOT NULL,
UNIQUE KEY `title-no` (`title-no`),
KEY `id` (`id`)
) ENGINE=MyISAM
AUTO_INCREMENT=9090949 DEFAULT CHARSET=latin1 AUTO_INCREMENT=9090949 ;
RESOLVED: The issue was not with this query. It was with a subsequent query. I was confused because I was only echoing this query. My bad. Thank you all for your support! :)
Try with:
$query = "SELECT * FROM Titles WHERE `Titles`.`title-no` = '" . $titleno . "'";
Here is a quick conversion to statement-based query (which is using MySQLi, adapt as necessary, your code or this example). The assumption is that the underlying prepared statement engine knows that you cannot specify a column name with placeholders in a prepared statement, so it should be passing it correctly (here's hoping :-)
$titleno=$_REQUEST['title_no'];
$statement=mysqli_prepare($your_mysqli_link, "SELECT `id` FROM `Titles` WHERE `title-no` = ?");
mysqli_stmt_bind_param($statement, 's', $titleno);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_result($statement, $found_id);
mysqli_stmt_fetch($statement);
echo "found id: $found_id";

php = insert working but want to check if in db already based on one field

Have a working system where I am posting news articles. I sometimes add the same one twice and want to avoid this. So how can I alter my insert statement to first check for a match on the field named 'title' to see if it is equal to the title I have in the record I am trying to submit?
Here is php code I use, as it was done for me since I am a PHP novice but I do not know how to check for the title=title and then not add it if it finds it or to add it if it doesnt find a match:
$result = mysql_query("
insert into news (
catalogid,
title,
intro,
content,
viewnum,
adddate,
rating,
ratenum,
source,
sourceurl,
isdisplay,
isfeature,
subip,
vsent,
timesubmitted)
values
('1',
'$title',
'$intro',
'$content',
'0',
'$subdate',
'$source',
'$icheck',
'N/A',
'$sourceurl',
'$isapp',
'0',
'127.0.0.1',
'0',
'$tsdate')"
);
Thank you!
There are database-specific tricks like on duplicate key update, but typically you simply test for the existence of a record with the same key via a select. If the record exists, you update it with the new data, otherwise you insert a new record.
You can run a check query before inserting , like:
$sql = mysql_query("SELECT catalogid from news WHERE title='".$yourTitle."'");
if(mysql_num_rows($sql) < 1) {
//add your insert query here
}
Hope that helps
$result = mysql_query("SELECT * FROM news WHERE `title`=$title");
if (!$result)
{
// your code INSERT
$result = mysql_query("
insert into news (
catalogid,
title,
intro,
content,
viewnum,
adddate,
rating,
ratenum,
source,
sourceurl,
isdisplay,
isfeature,
subip,
vsent,
timesubmitted)
values
('1',
'$title',
'$intro',
'$content',
'0',
'$subdate',
'$source',
'$icheck',
'N/A',
'$sourceurl',
'$isapp',
'0',
'127.0.0.1',
'0',
'$tsdate')"
);
}
You can't do this with a single INSERT statement, at least not directly. If you set the title field in your database table to UNIQUE, you can prevent MySQL from inserting a record with a duplicate title. You will need to detect if the mysql_query function returns FALSE; if it does, you know a duplicate record was inserted and you can handle this however you see fit.

Categories