I'm trying to add a null value into a database if the form field is left blank but not getting much luck...
Can anyone see where this is going wrong??
<?php
$con = mysql_connect("ipaddress","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
if (is_null($_POST["event_sub"]) || $_POST["event_sub"]=="") {
$event_sub = NULL;
} else {
$event_sub = mysql_real_escape_string($_POST["event_sub"]);
}
$sql="INSERT INTO myTable (event_sub)
VALUES
(". $event_sub .")";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
Perhaps try this:
if (is_null($_POST["event_sub"]) || $_POST["event_sub"]=="") {
$event_sub = 'NULL';
} else {
$event_sub = mysql_real_escape_string($_POST["event_sub"]);
}
Putting the NULL in single quotes will result in the word NULL being inserted into your query rather than an actual NULL, which is nothing.
why would you need to search for the word NULL? Just leave the insert for that column blank. and make sure allow null is set in the table..
Related
I am new in php so please help me here
I have one page for collect customer details and i did successfully
from databse table i want to pass 2 value
1- amount 2- personid
Table-
CREATE TABLE personal_info(
MTrackid bigint(20) AUTO_INCREMENT PRIMARY KEY,
MAmount varchar(50)
i write mysql query to pass value
<?php
$con = mysql_connect("localhost","testdb","root#123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$con = mysql_connect("localhost","testdb","root#123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$result = mysql_query("SELECT MTrackid,MAmount FROM personal_info");
while($rowval = mysql_fetch_array($result))
{
$trackid = isset($_GET['MTrackid']) ? $_GET['MTrackid'] : '';
}
mysql_close($con);
?>
and this is the code where i want to pass and show value
$TranTrackid=isset($_POST['MTrackid']) ? $_POST['MTrackid'] : '';
So please tell me where i am wrong and how to pass it and who where i want..
Thank in advance
I think what you want is to save the value from the SQL.
Then you should replace $_GET with $rowval. Because in $rowval will be your mysql result.
while($rowval = mysql_fetch_array($result))
{
if(isset($rowval['MTrackid'])) {
$trackid = $rowval['MTrackid'];
echo $trackid;
}
}
I have a table for "threads" and a table for "comments" on my database. Both tables have an auto increment ID column, timestamp etc. There is also a "THREAD ID" column where I'd like to INSERT thread's IDs in the "comments" table.
My question is: how can I retrieve the auto increment ID number of the related thread's row from "threads" table and INSERT this number to the "comments" table's "THREAD ID" column every time when I insert a comment. So I can create a link between "comments" and "threads".
I'm somewhat beginner at PHP and I'd like to learn with the explanation of the code. Like which string is for what, which method is for what..
<?php
/*show error codes*/
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
/* database info*/
define('DB_NAME', 'imageboard');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link1 = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link1) {
die('Could not connect: '.mysqli_error());
}
$db_selected = mysqli_select_db($link1, DB_NAME);
if (!$db_selected) {
die('Can\'t use' . DB_NAME . ': ' . mysqli_error());
}
//when pressed submit
if (isset($_POST['replySubmit'])) {
//buton ve textarea def
$deger = $_POST ['replyComments'];
$deger2 = $_POST ['replyNickName'];
$deger3 = $_FILES ['replyUserFile']['name'];
// WANT TO DEFINE THREAD ID HERE
//deger4 = $_POST [];
// SEND TO DATABASE
$sql1 = "INSERT INTO newReply (COMMENT, NAME, IMAGENAME) VALUES ('$deger', '$deger2', '$deger3')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
header('Location: ./thread.php');
}
}
?>
<?php
if(isset($_FILES['replyUserFile'])) {
$uploadName1 = $_FILES['replyUserFile']['name'];
$uploadTmp1 = $_FILES['replyUserFile']['tmp_name'];
$uploadType1 = $_FILES['replyUserFile']['type'];
// CORRECTION
$uploadName1 = preg_replace("#[^a-z0-9.,]#i", "_", $uploadName1);
// FILES TO directory
if(!$uploadTmp1) {
die("can't send...");
} else {
move_uploaded_file($uploadTmp1, "./images/$uploadName1");
}
$link1 = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link1) {
die('Could not connect: '. mysqli_error());
}
$db_selected1 = mysqli_select_db($link1, DB_NAME);
if (!$db_selected1) {
die('Can\'t use' . DB_NAME . ': ' . mysqli_error());
}
//INSERT INTO tables
$sql1 = "INSERT INTO images (USERIMAGENAME) VALUES ('$uploadName1')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
// CHANGE THE NAME OF THE IMAGE FILE IN THE DIRECTORY TO DATABASE ID NUMBER
$last_id = mysqli_insert_id($link1);
$ext1 = pathinfo("./images/$uploadName1", PATHINFO_EXTENSION);
rename("./images/$uploadName1", "./images/$last_id".".".$ext1);
// GO BACK TO THREAD
header('Location: ./thread.php');
}
}
mysqli_close($link1);
?>
I'm wondering why others suggest you to use mysqli_insert_id() when you want to get the thread_id. As I know, mysqli_insert_id() will return you the successfully inserted id of the last mysql query.
But here, when I check your code, you are not creating the thread here. It's something that has been already created (earlier).
What you trying to accomplish is (As I understand), you want to store the 'thread_id' in your 'comment' table as a reference to which thread this comment was posted, right?
My suggestion is to use a hidden field in your comment form and pass the thread_id to the submit page.
Then you can retrieve 'thread_id' too, in the same way you get the replyNickname, replyComment etc.
And then, use that 'thread_id' inside your query.
Ex:
//when pressed submit
if (isset($_POST['replySubmit'])) {
//buton ve textarea def
$deger = $_POST ['replyComments'];
$deger2 = $_POST ['replyNickName'];
$deger3 = $_FILES ['replyUserFile']['name'];
// WANT TO DEFINE THREAD ID HERE
$thread_id = $_POST ['thread_id']; // Note this line
//deger4 = $_POST [];
// SEND TO DATABASE
$sql1 = "INSERT INTO newReply (COMMENT, NAME, IMAGENAME, THREAD_ID) VALUES ('$deger', '$deger2', '$deger3', '$thread_id')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
header('Location: ./thread.php');
}
}
I hope what I understood is right. This is just a rough idea, you can pass the thread_id in anyway you want. But I don't see any point of using mysqli_insert_id() here.
//If the previous request triggered an auto increment
if (mysqli_insert_id($link)<>'') {
//retrieves the last ID
$lastID = mysqli_insert_id($link);
//do something
}
else {
//do something else...
}
Be sure that you chose INNODB engine in order to be able to handle foreign keys
Assuming you're using MySQL:
PDO (where $pdoConn is your PDO connection):
$yourlastID = $pdoConn->lastInsertId();
mysqli:
$yourlastID = $mysqli->insert_id;
If you are using MSSQL, use SCOPE_IDENTITY(). Read http://www.codeproject.com/Articles/103610/Difference-between-IDENTITY-SCOPE-IDENTITY-IDENT-C
create PROCEDURE [dbo].[spInsertIntoThreads]
(
#THREAD_ID int OUTPUT,
#Column1 varchar(50) = NULL,
)
AS
BEGIN
SET NOCOUNT ON;
Insert Into Threads(Column1)
values(#Column1);
SET #THREAD_ID=SCOPE_IDENTITY();
END
Hope it helps. :)
I have a little problem with my PHP code and database. Every time i refresh the page, a new empty row is being added to the database also when i open the page, what is the problem?
<?php
if (isset($_POST)) {
$con = mysql_connect("localhost","dwarfmaster","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_dwarfmaster", $con);
$name = $_POST['name'];
$release_year = $_POST['release_year'];
$publisher = $_POST['publisher'];
$genre = $_POST['genre'];
$sql = "INSERT INTO gamelist (name, release_year, publisher, genre)
VALUES
('$_POST[name]','$_POST[release_year]',
'$_POST[publisher]','$_POST[genre]')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
}
?>
to check if the request method is post, use:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
if(isset($_POST)) will always return true
or simply change
if (isset($_POST))
to
if (isset($_POST['name']))
you can add the following code-:
if( !empty(array_filter($_POST)) ) { . . Code to insert data into data base
from form . . }
if (isset($_POST))
will always return true !
try
if (isset($_POST['name'])&&isset($_POST['release_year'])
&&isset($_POST['publisher'])&&isset($_POST['genre']))
instead to check each time for each and every variable !
I have a database with 4 tables. (products,purchase,customer,user). When I tried to display all rows in products, no results. But in the user table, it displays. What should be the problem? Is it on my database?tables?php code?
Here's my code:
<?php
$db = mysqli_connect("localhost","root","", "prodpurchase");
if (!$db) {
die('Could not connect: ' . mysqli_error());
}
$sql = mysqli_query($db, "select * from user");
if( $sql === FALSE ) {
die('Query failed returning error: '. mysqli_error());
} else {
while($row=mysqli_fetch_array($sql))
{
echo $row['username']. "<br>";
}
}
?>
Hope you could help me.
Did you check the letters uppercase and lowercase in table columns?
You have inventory in your code, but in your question you named the table products, Is it this simple?
echo $row['item']. "<br>";
What is 'item'? Shouldn't you be selecting them by $row[0] or $row['products'].. or one of your other columns.
check your variables, for your example, try renaming your vairable $sql to something else, because you might have a similar variable somewhere in your code that you did not show.
try this :
<?php
$db = mysqli_connect("localhost","root","", "prodpurchase");
if (!$db) {
die('Could not connect: ' . mysqli_error());
}
$sqlstackoverflow = mysqli_query($db, "select * from user");
if($sqlstackoverflow === FALSE ) {
die('Query failed returning error: '. mysqli_error());
} else {
while($row=mysqli_fetch_array($sqlstackoverflow))
{
echo $row['username']. "<br>";
}
}
?>
Your code references an inventory table but you said your database has a products table (and no inventory table). Because of this, the query is failing.
Just Try With The Following :
<?php
$db = mysqli_connect("localhost","root","","prodpurchase");
if (!$db) {
die('Could not connect: ' . mysqli_error());
}
$sql = mysqli_query($db,"select * from user");
if( $sql === FALSE ) {
die('Query failed returning error: '. mysqli_error());
} else {
while($row=mysqli_fetch_array($sql,MYSQLI_ASSOC))
{
echo $row['username']."<br>";
}
}
?>
I think this may help you to resolve your problem.
I have a form which has a textbox with an attribute called ref. once this is submitted, it updates on of my fields in the database. I have this code working and fine but what i need now is for it to check if the data entered into the textbox exists in the database and if it does, then it should notify the user to choose another reference. here is my code for the php end:
$ref = mysql_real_escape_string($_REQUEST['ref']);
$id = $_GET['public'];
$con = mysql_connect("localhost", "*****", "******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('*****', $con);
$sql = "UPDATE public SET ref = '$ref' WHERE public_id = '$id'";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
any ideas guys?
thanks
You can get the number of rows affected:
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
//something WAS changed!
}
else {
//NOTHING was changed ... :-(
}
Also I would watch out for Bobby Tables
You might want to use mysqli or PDO's prepared queries for what you want to do.
Based on OP's comment below:
...
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
else {
//show some error message?
}
}
In this case First you run a select command to search for the record with particular reference number. If the result is eof , then run insert command. If not EOF then send a warning to the user saying reference number exist and choose another one.