Php 如何多次获取特定字段值。。我的输出通过内部联接来自两个不同的表
我想要两个表的输出..Php 如何多次获取特定字段值。。我的输出通过内部联接来自两个不同的表,php,mysql,database,image,Php,Mysql,Database,Image,我想要两个表的输出.. 一个表格用于产品\u详细信息和第二个表格用于产品\u图像 在产品图片表中,所有图片分别存储特定产品id的图片 我想要两个表的输出: 对于特定产品标识,来自产品详细信息表的所有详细信息和来自产品图像表的所有图像 我的代码: <?php error_reporting(0); $response = array(); $response1 = array(); require_once __DIR__ . '/db_Connect.php'; // check
一个表格用于产品\u详细信息和第二个表格用于产品\u图像 在产品图片表中,所有图片分别存储特定产品id的图片 我想要两个表的输出:
对于特定产品标识,来自产品详细信息表的所有详细信息和来自产品图像表的所有图像 我的代码:
<?php
error_reporting(0);
$response = array();
$response1 = array();
require_once __DIR__ . '/db_Connect.php';
// check for post data
if (isset($_GET["pro_id"])) {
$pid = $_GET['pro_id'];
// get a product from products table
//$result = mysql_query("SELECT * FROM product_list WHERE pro_id = '".$pro_id."'");
$q="SELECT product_list.pro_id,product_list.product_name,product_list.product_desc,product_images.image
FROM product_images
INNER JOIN product_list ON product_list.pro_id = product_images.pro_id
WHERE product_list.pro_id = '$pid'";
$res=mysql_query($q);
if (!empty($res)) {
// user node
$response["product"] = array();
$result = mysql_fetch_assoc($res);
//var_dump($result);
$count=count($result['image']);
$count++;
var_dump($count);
$product=array();
$product['pro_id']=$result['pro_id'];
//$product['cat_id']=$result['cat_id'];
$product['product_name']=$result['product_name'];
$product['product_desc']=$result['product_desc'];
//$product['image']="http://friendzfashionz.com/pandora/admin/".$result['image'];
$clr=array();
for($i=0;$i<$count;$i++)
{
$clr[$i]="http://friendzfashionz.com/pandora/admin/".$result['image'];
//var_dump($clr[$i]);
array_push($response1["images"], $clr[$i]);
}
$product['image']=$clr;
array_push($response["product"], $product);
$response["success"] = 1;
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
我在产品图片表中有两个不同的pro\u id图片我想要一次产品详细信息和该专业id的所有产品图片。
但问题是它给了我两次第一张照片 请帮助解决这个问题 产品详细信息表: 产品图片表:
问题是返回了两行,但只调用了一个
$result = mysql_fetch_assoc($res);
所以您只处理第一行
相反,在产品列表值上使用GROUP BY
,在
图像
这将为产品返回一行,其中包含逗号分隔的图像列表
然后,您可以使用EXPLODE()
分别获得一组图像
e、 g
另外,您仍然在使用mysql\u query()
,这在PHP5.5中被弃用,在PHP7中被删除。您应该在PDO或mysqli中使用参数化查询,否则当您升级PHP时,您的应用程序将崩溃,同时您将对SQL注入敞开大门
代码的问题在于使用了
mysql\u fetch\u assoc
函数。通过直接调用它,例如不将其包含在while循环中(如在的末尾),您只从数据库中获取一条记录。因此,count($result['image'])
语句将返回值1
。尽管您需要多条记录:product_images表中的每个图像一条记录
请注意,您使用的是mysql扩展。虽然从PHP7.0.0开始它就被删除了!改用mysqli或PDO。我修改了您的代码以使用mysqli,并对构建$response
数组做了一些更改
您可以阅读有关mysqli的使用,这些都是用来避免的
最后,对于正确的错误和异常处理,您应该阅读。然而,它专注于mysqli
index.php
请提供这两个表的创建表语法。您提供的代码是对ajax请求的响应吗?请显示ajax代码。代码以JSON格式响应我看到了。但是JSON响应是由ajax请求读取(例如捕获)的,还是仅仅打印在屏幕上?Paul,这是一个有趣的想法。尤其是你正确地分组(所有字段都没有聚合函数),这让我很欣赏你的答案。我从你的答案中注意到,我们似乎得出了相同的结论,你的方法看起来非常有效。我给OP留了一点时间来研究,因为我认为任何攻读硕士学位的人都应该阅读并理解他们在尝试什么。有人决定在40秒内否决我的这个和其他两个答案。。。对于决定否决我的答案的用户:请让我知道你否决的动机,以便我可以相应地更改我的答案。我愿意接受你的所有建议或批评,但请公平一点,让我有机会了解你的观点。通过这种方式,我们可以共同为网站的持续改进做出贡献。非常感谢。
$result = mysql_fetch_assoc($res);
SELECT pl.pro_id, pl.product_name, pl.product_desc,
GROUP_CONCAT(pi.image) AS 'images'
FROM product_images pi
INNER JOIN product_list pl ON (pl.pro_id = pi.pro_id)
WHERE pl.pro_id = ?
GROUP BY pl.pro_id, pl.product_name, pl.product_desc;
<?php
require __DIR__ . '/db_Connect.php';
// Array to hold the final response.
$response = array();
// Validate the product id.
if (!isset($_GET['pro_id']) || empty($_GET['pro_id']) || !is_numeric($_GET['pro_id'])) {
$response['success'] = 0;
$response['message'] = 'No product id provided.';
} else {
// Read the product id.
$productId = $_GET['pro_id'];
/*
* The SQL statement to be prepared. Notice the so-called markers,
* e.g. the "?" signs. They will be replaced later with the
* corresponding values when using mysqli_stmt::bind_param.
*
* @link http://php.net/manual/en/mysqli.prepare.php
*/
$sql = 'SELECT
pl.pro_id,
pl.product_name,
pl.product_desc,
pi.image
FROM product_images AS pi
INNER JOIN product_list AS pl ON pi.pro_id = pl.pro_id
WHERE pi.pro_id = ?';
/*
* Prepare the SQL statement for execution - ONLY ONCE.
*
* @link http://php.net/manual/en/mysqli.prepare.php
*/
$statement = $connection->prepare($sql);
/*
* Bind variables for the parameter markers (?) in the
* SQL statement that was passed to prepare(). The first
* argument of bind_param() is a string that contains one
* or more characters which specify the types for the
* corresponding bind variables.
*
* @link http://php.net/manual/en/mysqli-stmt.bind-param.php
*/
$statement->bind_param('i', $productId);
/*
* Execute the prepared SQL statement.
* When executed any parameter markers which exist will
* automatically be replaced with the appropriate data.
*
* @link http://php.net/manual/en/mysqli-stmt.execute.php
*/
$statement->execute();
/*
* Get the result set from the prepared statement.
*
* NOTA BENE:
* Available only with mysqlnd ("MySQL Native Driver")! If this
* is not installed, then uncomment "extension=php_mysqli_mysqlnd.dll" in
* PHP config file (php.ini) and restart web server (I assume Apache) and
* mysql service. Or use the following functions instead:
* mysqli_stmt::store_result + mysqli_stmt::bind_result + mysqli_stmt::fetch.
*
* @link http://php.net/manual/en/mysqli-stmt.get-result.php
* @link https://stackoverflow.com/questions/8321096/call-to-undefined-method-mysqli-stmtget-result
*/
$result = $statement->get_result();
/*
* Fetch data and save it into an array.
*
* @link http://php.net/manual/en/mysqli-result.fetch-all.php
*/
$productRecords = $result->fetch_all(MYSQLI_ASSOC);
/*
* Free the memory associated with the result. You should
* always free your result when it is not needed anymore.
*
* @link http://php.net/manual/en/mysqli-result.free.php
*/
$result->close();
/*
* Close the prepared statement. It also deallocates the statement handle.
* If the statement has pending or unread results, it cancels them
* so that the next query can be executed.
*
* @link http://php.net/manual/en/mysqli-stmt.close.php
*/
$statement->close();
/*
* Close the previously opened database connection.
*
* @link http://php.net/manual/en/mysqli.close.php
*/
$connection->close();
if (!$productRecords) { // No product records found.
$response['success'] = 0;
$response['message'] = 'No product data found.';
} else {
// Array to hold the final product data.
$product = array();
foreach ($productRecords as $productRecord) {
$productId = $productRecord['pro_id'];
$productName = $productRecord['product_name'];
$productDescription = $productRecord['product_desc'];
$productImage = $productRecord['image'];
if (!$product) { // Array is empty
$product[0] = array(
'pro_id' => $productId,
'product_name' => $productName,
'product_desc' => $productDescription,
);
}
$product[0]['image'][] = 'http://friendzfashionz.com/pandora/admin/' . $productImage;
}
$response['success'] = 1;
$response['product'] = $product;
}
}
echo json_encode($response);
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'tests');
define('USERNAME', 'root');
define('PASSWORD', 'root');
/*
* Error reporting.
*
* Also, define an error handler, an exception handler and, eventually,
* a shutdown handler function to handle the raised errors and exceptions.
*
* @link https://phpdelusions.net/articles/error_reporting Error reporting basics
* @link http://php.net/manual/en/function.error-reporting.php
* @link http://php.net/manual/en/function.set-error-handler.php
* @link http://php.net/manual/en/function.set-exception-handler.php
* @link http://php.net/manual/en/function.register-shutdown-function.php
*/
error_reporting(E_ALL);
ini_set('display_errors', 1); /* SET IT TO 0 ON A LIVE SERVER! */
/*
* Enable internal report functions. This enables the exception handling,
* e.g. mysqli will not throw PHP warnings anymore, but mysqli exceptions
* (mysqli_sql_exception).
*
* MYSQLI_REPORT_ERROR: Report errors from mysqli function calls.
* MYSQLI_REPORT_STRICT: Throw a mysqli_sql_exception for errors instead of warnings.
*
* @link http://php.net/manual/en/class.mysqli-driver.php
* @link http://php.net/manual/en/mysqli-driver.report-mode.php
* @link http://php.net/manual/en/mysqli.constants.php
*/
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create a new db connection.
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);