SELECT查询是否可能在Joomla DB中插入数据?

I need to check whether a value is in a DB. I am using

$db = JFactory::getDBO();
$query = $db->getQuery( true );

$query->select($db->quoteName('id'));
$query->from($db->quoteName('#__tablename'));
$query->where($db->quoteName('fieldname') . ' = ' . $db->quoteName($valuetocheck));
$db->setQuery($query);
$id = $db->loadResult();

echo "value = " . $id;

if($id) {/*action if the value already exists*/} else {/*...*/}

The problem is that every new value that I set to $valuetocheck is actually being inserted into the table. If I set a value that does not exist yet, it gets inserted, and so I always get a valid $id and cannot proceed to the else {}.

Is that possible? Is there any workaround to check whether a value is already inside?

Try this,

A SELECT query never insert any value to the DB If the data's are inserting in the table its should be somewhere else. Also instead of checking $id value you can check numrows as below.

$db = JFactory::getDBO();
$query = $db->getQuery( true );

$query->select($db->quoteName('id'));
$query->from($db->quoteName('#__tablename'));
$query->where($db->quoteName('fieldname') . ' = ' . $db->quoteName($valuetocheck));
$db->setQuery($query);
$db->query();
if($db->getNumRows() >0){
 //Data found
}
else{
 //Nod Data found
}

Hope it helps..

No, it is not possible. Any chance the db object gets reused differently in the code below?

  1. Try to add die('test 1'); just before the code you showed us and run to make sure for yourself that the table does not get changed. Don't mind that the website doesn't show anything.

  2. Then move the die-command to just after the echo-command and run again. There is in my mind no way valuetocheck has entered the table at this stage. Check!

  3. Continue testing when valuetocheck gets inserted..

Godo luck!