如何从MySQL表中检索数据并使用PHP将其插入到QR代码中?

时间:2014-10-03 08:34:03

标签: php mysql sql

我有这个PHP代码,用于创建包含给定数据的QR代码:

<?php

   include(JPATH_LIBRARIES . '/phpqrcode/qrlib.php');

   $tempDir = JPATH_SITE . '/images/';   
   $codeContents = 'This Goes From File';
   $fileName     = 'qr_'.md5($codeContents).'.png';

   $pngAbsoluteFilePath = $tempDir.$fileName;
   $urlRelativeFilePath = JUri::root() .'images/' . $fileName;

   if (!file_exists($pngAbsoluteFilePath)) {
      QRcode::png($codeContents, $pngAbsoluteFilePath);
   }
   else {
      echo "Not working!";
   }

   echo '<img src="'.$urlRelativeFilePath.'" />';

?>

我们需要的是连接到MySQL表(#__rsforms_submissions),检索一些字段(例如,名称和邮件,电话)并将它们插入QR代码而不是示例提供的数据。为此,我将检索登录用户的用户

$user = JFactory::getUser();
$username = JUserHelper::getUsername($user->id);

然后,MySQL查询看起来像

SELECT Name,Mail, Phone FROM #__rsforms_submissions WHERE Username = $username

然而,下一步是什么?如何将这些值插入PHP代码? 谢谢!

达尼

1 个答案:

答案 0 :(得分:1)

我假设你正在使用Joomla。我不知道Joomla,但我可以从selecting and retrieving SQL data找出来:

<?php

/* get username */
$user = JFactory::getUser();
$username = JUserHelper::getUsername($user->id);

/* get data from database */
// Get a db connection.
$db = JFactory::getDbo();

// Create a new query object.
$query = $db->getQuery(true);

// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('Name', 'Mail', 'Phone')));
$query->from($db->quoteName('#__rsforms_submissions'));
$query->where($db->quoteName('Username') . ' LIKE '. $db->quote('\'' . $username . '\''));
$query->order('ordering ASC');

// Reset the query using our newly populated query object.
$db->setQuery($query, 0, 1); // 0 = start, 1 = number of records
$row = $db->loadRow();

/* create the qrcode */
include(JPATH_LIBRARIES . '/phpqrcode/qrlib.php');

$tempDir = JPATH_SITE . '/images/';
$codeContents = $row->Name . ', ' . $row->Mail . ', ' . $row->Phone . ', '; // this is what goes into qrcode
$fileName     = 'qr_'.md5($codeContents).'.png';

$pngAbsoluteFilePath = $tempDir.$fileName;

if (!file_exists($pngAbsoluteFilePath)) {
  QRcode::png($codeContents, $pngAbsoluteFilePath);

  $urlRelativeFilePath = JUri::root() .'images/' . $fileName;
  echo '<img src="'.$urlRelativeFilePath.'" />';
}
else {
  echo "Not working!";
}

注意:未经测试!但是,它应该让你知道如何做到这一点。