get minimum value from sql table using PHP - php

I want to get the minimum/smallest ID from SQL table where condition matches using PHP, I tried the below code but an error has occurred, ie
Trying to get property of non-object in /var/www/html/site/sitename/project-name.php on line 14
Any suggestion is highly appreciated, thanx
$query = "select MIN(id) FROM project_view WHERE project_id = '$projectId' and email = '$email_in_cookie'";
$result = $con->query($query);
if( $result->num_rows > 0 )
{
$row = $result->fetch_assoc();
$sectionID = $row['id'];
}
echo $sectionID;

Related

how to get value from select query?

How to get value from select query without using while loop while we know that output is defiantly only one record
$sql = "SELECT id FROM MyGuests";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
echo $row["id"];
}
Here if i know that there is only one record comes as a output then how to avoid while loop and directly get our id
just delete the while loop!
$sql = "SELECT id FROM MyGuests";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["id"];
are you using mysql_* functions by any chance? please switch to PDO as soon as possible.
You can use MYSQl bind result if its a single row output
if( isset($con) && !empty($con) && $con!="" ) {
$knownStmt=mysqli_prepare($con, "SELECT id FROM MyGuests");
if( $knownStmt ) {
mysqli_stmt_execute($knownStmt);
mysqli_stmt_bind_result($knownStmt,$id);
mysqli_stmt_fetch($knownStmt);
mysqli_stmt_close($knownStmt);
}
}
Please try this. This is one of the best way. You can also pass the where condition also and bind the value this query. Please see below is the example for the same.
if( isset($con) && !empty($con) && $con!="" ) {
$knownStmt=mysqli_prepare($con, "SELECT name FROM MyGuests WHERE id=?");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$UID);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_bind_result($knownStmt,$Name);
mysqli_stmt_fetch($knownStmt);
mysqli_stmt_close($knownStmt);
}
}
I'm sure this will definitely help you.
Please note this works only for single row result.
You can use this code for your purpose.
$result = mysql_query("SELECT id FROM MyGuests");
$row=mysql_fetch_array($result);
echo $row["id"];

mysqli_assoc + json_encode does not return first row

$sql= "SELECT team_name AS label, user_id as value
FROM d_getreal_captains ORDER BY team_name ASC";
$result = $bfit_connect->query($sql);
$rows = mysqli_fetch_assoc($result);
while( $rows = mysqli_fetch_assoc( $result ) ) {
$json[] = $rows;
}
This code works as expected except it does not return the first record from the table (i.e. the first team_name and user_id). I have seen that other people have suggested the fix of using mysql_data_seek to reset the row index, but I also know that is deprecated and would like my fix to be utilizing a current method. And ideas or advice is appreciated... thanks.
You're calling mysqli_fetch_assoc() outside of your loop which is popping the first result off of the result set. You aren't using the values anywhere so you can safely remove it.
$result = $bfit_connect->query($sql);
$rows = mysqli_fetch_assoc($result); // <-- remove this
$sql= "SELECT team_name AS label, user_id as value
FROM d_getreal_captains ORDER BY team_name ASC";
$result = $bfit_connect->query($sql);
//Here you used to take the first row out with mysqli_fetch_assoc, I removed this line
while( $rows = mysqli_fetch_assoc( $result ) ) {
$json[] = $rows;
}

PHP count from database WHERE

I am trying to show a count of all applications stored in a database with the status of 1.
Here is my UPDATED code:
$result=mysql_query("SELECT * FROM member ")or die('You need to add an administrator ' );
$counter = mysql_query("SELECT COUNT(*) as personID FROM member where state='1' ");
$row = mysql_fetch_array($result);
$personID = $row['personID'];
$num = mysql_fetch_array($counter);
$countadmin = $num["personID"];
However this isn't showing anything when I echo `$countadmin'
Can anyone help
You may try this
$query = mysql_query("select count(*) from member where state='1'");
if ($query) {
$count = mysql_result($query, 0, 0);
echo $count;
}
Check mysql_result and also notice the Warning at top. Also make sure that, the field is state not status, it's confusing, you mentioned status in your question but used state in the query.
Also, following line is not required to get the count of your second query
$result=mysql_query("SELECT * FROM member ")or die('You need to add an administrator ' );
Also, make sure that, you have connected to a database and selected it.
You try to readout "ID", but you select COUNT as "personID"
You have two options here;
$result = mysql_query("SELECT * FROM `member` WHERE `Status`='1'");
$num_rows = mysql_num_rows($result);
or
$result = mysql_query("SELECT COUNT(`Status`) FROM `member` WHERE `Status`='1'");
while($row = mysql_fetch_array($result)){
$Count = $row['count(Status)'];
}

php variable in a select query

I am pretty sure this is a syntax problem, but there may be other issues as well.
Ultimately, I'm trying to create a variable from an array that will be used in an insert statement, but I can't get past a select statement with a variable.
For a while I had $country_id = $coun; as $country_id = mysqli_real_escape_string($coun); but the var_dump suggested that the mysql_real_escape_string was preventing $country_id from taking on the value of $coun.
When I check for errors on $q, the query it spits out works just fine on phpmyadmin, yet the array outputs a NULL value.
I'm stumped.
Here is the code:
//get short_name variable
$country_id = $coun;
//var_dump($coun, $country_id);
$q = "SELECT short_name FROM country WHERE country_id = $country_id LIMIT 1";
$r = mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if ($num > 0) {//match was made
//Get short_name
$row = mysqli_fetch_assoc($r, MYSQLI_ASSOC);
//var_dump($row);
}else {
echo '<p>no match</p>';
}
I just got some help and it turns out that the problem was that "assoc" should have been "array." it looks like this now. $row = mysqli_fetch_array($r);

Converting from mysql to mysqli (mysql_fetch_array) [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I have some php code that was like this:
$row = mysql_fetch_array ( mysql_query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
I'm now trying to convert it to mysqli_fetch_array as shown here http://php.net/manual/en/mysqli-result.fetch-array.php (Example #1 Object oriented style)
I'm not sure what the example means by "$result".
This is what I've converted my code to so far:
<?php
include('../config.php');
if (isset($_GET['uid']) ) {
$uid = $_GET['uid'];
$id = $_GET['id'];
if (isset($_POST['submitted'])) {
foreach($_POST AS $key => $value) { $_POST[$key] = mysqli_real_escape_string($value); }
//Query for tblFacilityHrs
$sql = " UPDATE tblFacilityHrs SET `title`='{$_POST['title']}',`description`='{$_POST['description']}' WHERE `uid` = '$uid' ";
$result = $mysqli->query($sql) or die($mysqli->error);
//Query for tblFacilityHrsDateTimes
$sql2 = "UPDATE tblFacilityHrsDateTimes SET `startEventDate`='{$_POST['startEventDate']}',`endEventDate`='{$_POST['endEventDate']}', `startTime`='{$_POST['startTime']}',`endTime`='{$_POST['endTime']}',`days`='{$_POST['days']}',`recurrence`='{$_POST['recurrence']},`finalDate`='{$_POST['finalDate']}' WHERE `id` = '$id' "; print $sql2;
$result2 = $mysqli->query($sql2) or die($mysqli->error);
echo ($mysqli->affected_rows) ? "Edited row.<br />" : "Nothing changed. <br />";
echo "<a href='list.php'>Back</a>";
}
$row = $result->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
$row2 = $result2->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'"));
?>
There is probably a lot wrong with as I am learning mysqli, but right now it errors on
Fatal error: Call to a member function fetch_array()
UPDATE queries do not return result objects, it returns TRUE (assuming success). You're then trying to call TRUE->fetch_array(), which obviously won't work.
Now, for doing what you actually want to do, try this:
$row = $mysqli->query("SELECT.....")->fetch_array();
Looks like you are trying to use an old result object (result of your UPDATE) to get results for a new query. You need to run the new query first, assign its result to an object, and then fetch the results from object. Check out the last three lines of your script re-written:
$facilityHoursQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'");
$facilityHoursDateTimesQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'");
$facilityHoursRow = $facilityHoursQueryResult == FALSE ? NULL : $facilityHoursQueryResult->fetch_array();
$facilityDateTimesRow = $facilityHoursDateTimesQueryResult == FALSE ? NULL : $facilityHoursDateTimesQueryResult->fetch_array();
?>
Here is a helpful page with other result object methods:
http://www.php.net/manual/en/class.mysqli-result.php

Categories