简体   繁体   English

PDO取得最大价值

[英]PDO Fetch Largest Value

I have been researching for the past hour with no luck, i've tried so many methods. 在过去的一个小时里,我一直在研究,没有运气,我尝试了很多方法。 All I want to do to is get the largest value from a certain column in a table and store it in a variable in php that I can use for whatever I want. 我要做的就是从表中的特定列中获取最大值,并将其存储在php中的变量中,该变量可用于我想要的任何内容。 Here's where I'm at so far: 这是我到目前为止的位置:

$link = new PDO('mysql:host=****;dbname=****;charset=UTF-8','****','****');
$gid = $link->prepare("SELECT MAX(Group_ID) as maxGroup FROM Conference");
$gid->execute();
$test = $gid->fetch(PDO::OBJ);
echo $test;

At this point I don't even know if OBJ is correct, I'm just trying so many different things. 在这一点上,我什至不知道OBJ是否正确,我只是在尝试许多不同的事情。 Can anyone help me out, what do I need to do? 谁能帮我,我该怎么办? I just want to get the largest value and store it in a variable. 我只想获得最大的值并将其存储在变量中。

You are returning an object, so you need to access the properties accordingly: 您正在返回一个对象,因此您需要相应地访问属性:

echo $test->maxGroup;

The ->fetch(PDO::OBJ); ->fetch(PDO::OBJ); returns the results of the query and creates an object with properties based on the columns/aliases you have in your query. 返回查询的结果,并根据查询中的列/别名创建具有属性的对象。

Edit: If you are just trying to return the results and trying a few different ways, why not just do it in a simple way: 编辑:如果您只是尝试返回结果并尝试几种不同的方法,为什么不以简单的方式进行操作:

$test = $sth->fetch(PDO::FETCH_ASSOC);
echo $test['maxGroup'];

Why not directly association? 为什么不直接关联?

$link = new PDO('mysql:host=****;dbname=****;charset=UTF-8','****','****');
$gid = $link->prepare("SELECT MAX(Group_ID) as maxGroup FROM Conference");
$gid->execute();
$test = $gid->fetch(PDO::FETCH_ASSOC);
echo $test['maxGroup'];

i create a simple function for who want to use it simple but helpfull for the pdo() it's a simple function i know from my heart that you know what i mean with it 我为想要使用它的人创建了一个简单函数,但对pdo()却很有帮助,这是一个简单的函数,我从心底就知道我对它的含义

function last_inserted($column,$table){
 $dbh = pdo();
 $gid = $dbh->prepare("SELECT MAX(".$column.") as maxGroup FROM ".$table);
 $gid->execute();
 $last = $gid->fetch(PDO::FETCH_ASSOC);
 return $last['maxGroup'];
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM