Wrox Programmer Forums
Go Back   Wrox Programmer Forums > PHP/MySQL > PHP How-To
|
PHP How-To Post your "How do I do this with PHP?" questions here.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the PHP How-To section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old January 13th, 2004, 01:55 PM
Authorized User
 
Join Date: Jan 2004
Posts: 33
Thanks: 0
Thanked 0 Times in 0 Posts
Default INSERT INTO..no error but nothing is inserted!!

hello..:D
now i'm having this strange problem...
my snippet of code:
Code:
<?php
include("../inc/config.php");

     $query =mysql_query( "Select * from rujAduan");
          if ($query.$EOF) {

        $query =mysql_query("INSERT INTO rujAduan(ref) VALUES(".$HTTP_POST_VARS["rec"].") ");
        $result=$query;

        } else {

        $query =mysql_query("UPDATE rujAduan SET ref = ".$HTTP_POST_VARS["rec"]." ");
        $dbq=$query;

    }


    $sqlquery =mysql_query("INSERT INTO aduanKerosakan(idAduan,tarikhAduan,idMajor,idMinor,pelapor,waktuAduan,punca,status) VALUES(".$HTTP_POST_VARS["ID"].",".$HTTP_POST_VARS["hariIni"]." ,".$HTTP_POST_VARS["major"].",".$HTTP_POST_VARS["minor"].",".$HTTP_POST_VARS["idPekerja"].",".$HTTP_POST_VARS["jam"].",".$HTTP_POST_VARS["kerosakan"].",".$HTTP_POST_VARS["status"].") ");
?>
everything is fine..i mean no error appear...
but nothing is inserted except in table rujAduan..
in table aduanKerosakan where alot of data i want to insert,there is nothing in there...
how to fix this??
quasedillas5...can u help me again???

 
Old January 13th, 2004, 03:10 PM
richard.york's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Hey Apek, more troubles so soon!

Well you have a couple of problems, one you aren't reporting errors from mysql. So if something goes wrong in the database side of things you are left in the dark.

Try using this database query wrapper function, it simplifies including mysql error rreporting. It will display errors if your display_errors directive of php.ini is turned on, this is so you can turn off your custom error reporting in a live enviornment.

One thing that you aren't doing in your queries is quoting strings, strings must be quoted in a query... if you have mysql error reporting in place you'd see error messages to that effect.

Consider the structure of an INSERT query:

INSERT INTO `table` (`col`, `col2`) VALUES (1, 'a string');

You see? An integer can be unquoted, a string must be delimited by single quotes.

Another thing I need to point out is use $_POST not $HTTP_POST_VARS.. you want your code to work on future versions of PHP! The $HTTP_*_VARS way is deprecated, and I've read that PHP 5 won't support it.

The $link argument of this query function is expected to contain the mysql-link resource handler that you set with a call to mysql_connect, customize that to your needs.

Code:
<?php
include("../inc/config.php");

    function query($query, $link, $line, $file)
    {
        $result = mysql_query($query);

        if (empty($result) && ini_get('display_errors') == 1)
        {
            echo mysql_error().": ";
            echo mysql_errno()."<br />\n";
            echo $query."<br />\n";
            echo "@ $line in $file\n";
        }

        return $result;
    }

    // forgot to include the arguments!
    $query = query("SELECT * FROM rujAduan", $link, __LINE__, __FILE__);   
     
    if (!empty($query))
    {
        $query = query("INSERT INTO rujAduan(ref) VALUES('{$_POST["rec"]}')", $link, __LINE__, __FILE__);

        // Why do you assign the value of query to result??
        $result = $query;
    }

    else
    {
        $query = query("UPDATE rujAduan SET ref = '{$_POST["rec"]}'", $link, __LINE__, __FILE__);
        $dbq = $query;
    }


    $sqlquery = query("INSERT INTO aduanKerosakan(idAduan,tarikhAduan,idMajor,idMinor,pelapor,waktuAduan,punca,status) VALUES('{$_POST["ID"]}', '{$_POST["hariIni"]}', '{$_POST["major"]}', '{$_POST["minor"]}', '{$_POST["idPekerja"]}', '{$_POST["jam"]}', '{$_POST["kerosakan"]}', '{$_POST["status"]}')", $link, __LINE__, __FILE__);

?>
: )
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
 
Old January 13th, 2004, 11:07 PM
Authorized User
 
Join Date: Jan 2004
Posts: 33
Thanks: 0
Thanked 0 Times in 0 Posts
Default

thanks...
now its working....

Quote:
quote:
function query($query, $link, $line, $file)
    {
        $result = mysql_query($query);

        if (empty($result) && ini_get('display_errors') == 1)
        {
            echo mysql_error().": ";
            echo mysql_errno()."<br />\n";
            echo $query."<br />\n";
            echo "@ $line in $file\n";
        }

        return $result;
    }
u suggest me to use that..
i did and it well done..
but for your info, i dont know what the code means..
can u xplain it to me??
just want to learn here...
and why at the end every query u put $link, __LINE__, __FILE__?
what its function???


and why the insert operation cannot insert data to datetime datatype??
the $_POST["jam"] and $_POST["kerosakan"] will be inserted to the datetime field..
but when i check mysql,there always show 0000-00-00 00:00:00,no matter what i put in the input textbox it still record 0000-00-00 00:00:00.
what do u think?
should i change the datatype?
how to use the datetime datatype correctly??
 
Old January 14th, 2004, 01:05 AM
richard.york's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Apek! Delighted to hear you've got it working.

OK 1st the extra arguments...

$link refers to the mysql-link resource handler.. in place of $link use what you set in the call to mysql_connect() or mysql_pconnect(), the function that you use to create the link to the database resource.

So if you do this:

$link = mysql_connect('localhost', 'user', 'pass');

Then you would pass $link as an argument to the query() function, and the reason for this is two fold, the first reason being $link is set in global scope and because of variable scoping rules, mysql_query() won't automatically pick up on its existence as it does when you simply make a call to mysql_query() in global scope without the database wrapper function. The second reason is when making wrapper functions you should plan to have at minimum the ability to take all the arguments that the original function takes, in this case that being the mysql_query() function which takes two arguments, the first being the query string and the second an optional reference to the variable containing the mysql-link resource handler.

Here is something that I do:

I make each of these extra arguments optional, and then I can fill in the values if I think it will be important to have the extra information. I would make $link optional, because in my scripts I only make a call to mysql_connect() once, and only connect to a single database.

If I place its value in a superglobal, then I can import it into the function, this is nice because it eliminates the need to include it as an argument, and if I really need to specify it explicitly, I can.

__LINE__ and __FILE__ are special "magical" predefined constants, I include these because if you are working on a large project and a query fails it will help you to go directly to the source of the problem... I have scripts that can quickly grow to 2000 or so lines.. in all that you might forget where you make this or that query!

__LINE__ will be the line number that the query appears on, and __FILE__ will be the absolute path to the php script. These are considered "magical" in that they change dynamically based on where in a script you use them.

// Place the mysql link handler in the $GLOBALS suberglobal array
// It will be available in $link AND in $GLOBALS["link"] while in global scope
// (outside of a function or class) it will be available in $GLOBALS["link"] only
// while inside of a function or class.

$GLOBALS["link"] = mysql_connect('localhost', 'user', 'pass');


    function query($query, $line = null, $file = null, $link = null)
    {

        // Automatically import the value of $GLOBALS["link"];
        // if $link does not contain a value.
        if (is_null($link))
        {
                $link = $GLOBALS["link"];
        }

        $result = mysql_query($query, $link);

        if (empty($result) && ini_get('display_errors') == 1)
        {
            echo mysql_error().": ";
            echo mysql_errno()."<br />\n";
            echo $query."<br />\n";

            if (!is_null($line))
                    echo "@ line: $line ";

            if (!is_null($file))
                    echo "in file: $file<br />\n";
        }

        return $result;
    }

Using the above you can make queries like this:

$result = query("SELECT * FROM `mytable` WHERE `this` = that'", __LINE__, __FILE__);

I left off the $link argument, because now that I've rewritten the function to import it automatically we don't need to specify it explicitly.

I also left off a quote mark in the query.

This will produce error output like this:

#1064: You have an error in your SQL syntax near ''' at line 1
SELECT * FROM `mytable` WHERE `this` = that'
@ line: 1 in file: G:\www\test.php

All that make sense?

Some urls to browse:
http://www.php.net/mysql_query
http://www.php.net/mysql_error
http://www.php.net/mysql_errno
http://www.php.net/manual/en/languag...predefined.php

OK your other question:
Quote:
quote:
and why the insert operation cannot insert data to datetime datatype??
the $_POST["jam"] and $_POST["kerosakan"] will be inserted to the datetime field..
but when i check mysql,there always show 0000-00-00 00:00:00,no matter what i put in the input textbox it still record 0000-00-00 00:00:00.
When you create a date/time field, you need to use MySQL functions to specify the time, or structure your string to the exact format of the field.

Example:
INSERT INTO `time` VALUES(now());

Will insert: 2004-01-13 23:56:58

OR

INSERT INTO `time` VALUES('2005');

Will insert: 0000-00-00 00:00:00

OR

INSERT INTO `time` VALUES('2005-01-13 23:56:58');

Will insert that exact string.

If you want a custom time, I would suggest changing the field type to CHAR (a fixed character length) And use PHP to generate a timestamp, I would suggest using UNIX timestamps which are a bit more compatible with the PHP functions mktime() and date() and just IMO more flexible overall. date() will take a UNIX timestamp and format it however you like.

More information:
http://www.php.net/date
http://www.php.net/mktime
http://www.mysql.com/doc/en/DATETIME.html

: )
Rich



:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
 
Old January 14th, 2004, 01:20 AM
richard.york's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Oops I got this one backwards:

echo mysql_error().": ";
echo mysql_errno()."<br />\n";

Will produce:
You have an error in your SQL syntax near ''' at line 1: #1064

I don't think it matters.
My explaination of how mysql_query() works is also a bit off, it basically looks for the last opened link to the database resource, if that isn't found it attempts to login using mysql_connect() with no arguments, regardless of that, in a wrapper function, or in a function at all, it is best to specify it lest strange bugs emerge! Best to read that manual page, it will help you understand the idiosyncrasies and inner workings of the function!

: )
Rich


:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
 
Old January 14th, 2004, 02:36 AM
Authorized User
 
Join Date: Jan 2004
Posts: 33
Thanks: 0
Thanked 0 Times in 0 Posts
Default

hmmm...for the time being, ijust change the datatype to char like u said..
maybe later on i can format it the way i like..
and i'm waiting what problem will rise after this..
get ready quasedilla5!:D

now i have a new pronblem...heheh..
I have a submit form that is managed with PHP. On the form, there has to be a reference number that has to be incremented every time a user submits.And the reference number interacts with mysql..

heres my code:
Code:
//---------------------------------------
   //            DATE FUNCTION
   //---------------------------------------
   $Tdate = getdate();
    $datToday = date("d/m/Y");
    $year=$Tdate['year'];
   //---------------------------------------
   //          REFFRENCE NUMBER
   //---------------------------------------

    $query = "Select * from ".$DBprefix." rujAduan";
    $logCursor = mysql_query($query);

    if ($logCursor.$EOF) {
        $refNum = 1;
    } else {
        $refNum = $logCursor["ref"] + 1;
    }

    if ($refNum < 10) {
          $refNumber = "00".$refNum;
     } else {
          if ($refNum < 100) {
              $refNumber = "0".$refNum;
          } else {
              $refNumber = $refNum;
          }
        }

    $referNum = "REF".$refNumber."/".$year;
?>
the output is like REF001/2004..
but when i submit it again,it still show REF001/2004..
it suppose to show REF002/2004 (increment by 1)..
wheres the error??
hmm...help!!!!!!!!!


 
Old January 14th, 2004, 04:18 AM
Authorized User
 
Join Date: Jan 2004
Posts: 33
Thanks: 0
Thanked 0 Times in 0 Posts
Default

hmmm..i try to check in my mysql database..
theres a strange thing happens...
the rujAduan table is consist of "ID" and "ref" field...
suppose the "ref" field is increased by 1...(look at the code)
but why must the ID field is increase?
haaaaaa.......HELP!!!!!!!!!!!

 
Old January 14th, 2004, 02:38 PM
richard.york's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Quote:
quote:
#1064: You have an error in your SQL syntax near ''' at line 1
SELECT * FROM `mytable` WHERE `this` = that'
@ line: 1 in file: G:\www\test.php
By the way, the line number in the MySQL error refers to the query not the script.
Whereas the line number we input to the bottom of the error output refers to the script, not the query.

I just wanted to be sure that was clear!

Code:
    // Use the query function we just discussed above~ trust me it will save you headaches!
    // ALWAYS use EVERY possible error reporting device when developing

    $result = query("SELECT * FROM ".$DBprefix." rujAduan", __LINE__, __FILE__);

    // You do not fetch the array first
    // http://www.php.net/mysql_fetch_array

    $logCursor = mysql_fetch_array($result, MYSQL_ASSOC);

    // Where are you getting .$EOF ?? 
    // You do not show this variable being created
    // My guess is you are trying to use syntax from another language there.

    if (empty($logCursor["ref"]))
    {
        $refNum = 1;
    }

    else
    {
        $refNum = $logCursor["ref"] + 1;
    }

    if ($refNum < 10)
    {
        $refNumber = "00".$refNum;  
    }

    else
    {
        if ($refNum < 100)
        {
            $refNumber = "0".$refNum;
        }

        else
        {
            $refNumber = $refNum;
        }
    }

    $referNum = "REF".$refNumber."/".$year;

: )
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::
 
Old January 15th, 2004, 12:14 AM
Authorized User
 
Join Date: Jan 2004
Posts: 33
Thanks: 0
Thanked 0 Times in 0 Posts
Default

hmm..i think i must use what u said...
but can i ask another question here?
the reference number is working..
BUT...why in mysql (table rujAduan) shows this:

id ref
------------
34 5
33 4
32 3
31 2
30 1

all i wanna do is it shouldn't insert a new line everytime to generate the reference numnber..

want i want is when a first time user submit a reference number,the table rujAduan will show this:

id ref
----------
1 1

and when the second time:

id ref
----------
1 2

and so on..the ref number is added by one according to the user submit without adding a new line in mysql database...and thats what the code doing isn't it?
but why it keeps adding a new line??

FYI the datatype for id is int with auto increment and ref is just int...



 
Old January 16th, 2004, 02:43 PM
richard.york's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 1,706
Thanks: 0
Thanked 6 Times in 6 Posts
Default

Quote:
quote:
all i wanna do is it shouldn't insert a new line everytime to generate the reference numnber..

want i want is when a first time user submit a reference number,the table rujAduan will show this:
Hey Apek, sorry about the delay. I guess I don't understand what you're trying to do if you don't want the id field to auto-increment, then remove the auto-increment attribute.

: )
Rich

:::::::::::::::::::::::::::::::::
Smiling Souls
http://www.smilingsouls.net
:::::::::::::::::::::::::::::::::





Similar Threads
Thread Thread Starter Forum Replies Last Post
Insert Query Error & Run-Time Error 3022 DavidWE Access 1 July 31st, 2008 11:17 AM
Inserted Identities hossrad SQL Server 2005 1 May 21st, 2007 09:48 AM
Record is Inserted Twice donevco Access 1 February 27th, 2007 12:28 PM
How can I get the last inserted rows? fraijo SQL Server 2000 4 November 23rd, 2006 07:50 AM
Double records inserted when using Insert Sach Classic ASP Databases 4 March 7th, 2006 02:29 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.