MySQL Query Enum - php

I have been working on this for a while now, I know it's simpler than what I am making it, but I just can't get it. I have some code where I am trying to query an enum either 1 or 0 from my table so this is exactly what I have to do this.
$username = 'test'
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='.$username.'");
Now I have all the connection stuff down I think, I get no errors there, but when I print this thing out in my echo I get this,
Heres my echo:
echo 'Hello, '.$username.', you Result is: '.$passResult.'!';
What I want to get is:
Hello, test, your Result is: 1
or
Hello, test, your Result is: 0
Now what I get is:
Hello, test, your Result is: Resource id #6
Now no matter what I do I get the same thing, I have no idea what I'm doing wrong here guys if someone could point this out that would be awesome. What this enum is being use essentially for a boolean just to see if the user has personally set a password not the computer generated version.

mysql_query returns a result resource, essentially a pointer to the memory where the results are buffered. That result set can contain many rows, as you can select many rows, so you need to fetch the row(s) you want then the column(s) you want from those rows.
/* execute the query and get a result resource back */
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='" . mysql_real_escape_string($username) . "'");
/* retrieve the first row from $passResult */
$row = mysql_fetch_assoc($passResult);
/* assign the usrSetPass column's value from that row to $passed */
$passed = $row['usrSetPass'];
Also, your query is wrong. You enclosed it in double quotes, so you're not actually breaking out of the string and concatenating $username when you use the single quotes and dots inside. I've corrected it above.

mysql_query doesn't return a value, it returns a resource (see here in the manual).
The returned result resource should be passed to another function for dealing with result tables (like mysql_fetch_array() or mysql_fetch_assoc()), to access the returned data.
Example based on your initial code:
$username = 'test';
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='".$username."'");
while ($row = mysql_fetch_assoc($passResult)) {
echo $row['usrSetPass'];
}

Related

how to subtract a specific amount from the COUNT(*) result

I'm new to PHP and i want to know how i can subtract a specific amount from the results from counting the total amount of rows in a table. In this case i'd like to minus the value 3 from whatever the value of the total rows is. But i keep getting an error. Below is my code.
$cartwork = $con->query("SELECT count(*) FROM table");
$vs = '3';
$camount = $cartwork - $vs;
echo "$camount";
When the code runs i get the error "Object of class mysqli_result could not be converted to int" what can i do to fix this and get it to work properly.
The query returns a result set. You need to parse through the result set(s) in order to access the values returned. That's basically what the error states.
Please see here for documentation on the PHP function for fetching rows:
http://php.net/manual/en/function.mysql-fetch-row.php
So basically you would need
$row=$cartwork->mysql_fetch_row();
$cartWork_value = $row[0];
$vs = '3';
$camount = $cartwork_Value - $vs;
echo "$camount";
Note - this assumes that you get back exactly one result row (which should be the case with your query).
You can simply change your query to:
$cartwork = $con->query("SELECT count(*)-3 FROM table");
It doesn't smell particularly good though.

counting rows in php with sql

For an application I'm trying to count the total of friends. I want to do this with a function but it isn't returning anything. It tells me this:
Warning: mysqli_query() expects at least 2 parameters, 1 given
But I only need one parameter. I think I'm totally wrong.
This is the function:
public function GetTotalOfFriends($user_id){
$db = new Db();
$select = "SELECT COUNT FROM friendship WHERE (friendship_recipient_id ='" . $user_id ."' OR friendship_applicant_id = '" . $user_id . "') AND friendship_status = 'accepted'";
$result = $db->conn->query($select);
$row = mysqli_query($result);
$total = $row[0];
echo $total;
I'm trying to print it out in this way:
$friend = new Friendship;
$numberoffriends = $friend->GetTotalOfFriends($user_id);
<?php echo $numberoffriends; ?>
You are mixing up a couple of things. The line $result = $db->conn->query($select); already seems to execute a query, but then you try to bypass your database wrapper by passing that query result again to mysqli_query.
Apart from that, I think your query itself is also wrong. COUNT needs a parameter, indicating a field or value to count. Quite often COUNT(*) is used, but COUNT('x') might be more efficient in some cases. You can also use a specific field name, and COUNT will count the non-null values for you.
The result you got is a mysql_result object, which you need to use to get to the actual data of the query result.
The documentation of this object is here and I suggest that you read it thoroughly.
One possible way to do this is using this:
$resultArray = $result->fetch_row();
This will result in the first (and only) row of your query. It is represented as an array, with one value (since your query returns only one column). You can fetch that value like this:
return $resultArray[0];
You could also use any of the other fetch methods if you want your data in a different fashion.

table doesnt exist

I have created a query that loops through a group of table ID's to get a sum of their combined values. with error handling i get a "Table 'asterisk.custom_' doesn't exist" error and the query is killed obviously. but if i remove the error handling then i get an "mysql_fetch_array() expects parameter 1 to be resource" and the query completes as it should.
Thank in advance for your help.
include("currentday.php");
//---used for testing passing variables
//echo $customID[0];
//echo "<br>".$numrows;
$i = 0;
while($i<=$numrows)
{
mysql_select_db("asterisk") or die(mysql_error()); //This line determines the database to use
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
sum(vicidial_agent_log.pause_sec) as sumPause,
sum(custom_$customID[$i].d_amt) as sumDamnt,
sum(custom_$customID[$i].up_amt) as sumUpamnt,
sum(custom_$customID[$i].md_amt) as sumMdamnt,
sum(custom_$customID[$i].s_amount) as sumSamnt,
sum(vicidial_agent_log.dispo_sec)
FROM
vicidial_agent_log
INNER JOIN
vicidial_users
ON
(vicidial_agent_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$i]
ON
(vicidial_agent_log.lead_id = custom_$customID[$i].lead_id)
WHERE
vicidial_users.user = 'tcx'
GROUP BY
vicidial_users.full_name
ORDER BY
vicidial_agent_log.event_time DESC
";
$queryResult = mysql_query($query);// or die(mysql_error());
while ($rowResult = mysql_fetch_array($queryResult))
{
$pauseResult[] = $rowResult["sumPause"];
$sumdamntResult[] = $rowResult["sumDamnt"];
$sumupamntResult[] = $rowResult["sumUpamnt"];
$summdamntResult[] = $rowResult["sumMdamnt"];
$sumsamntResult[] = $rowResult["sumSamnt"];
}
//print_r($pauseResult);
//echo $pauseResult[0];
$i++;
}
Update:
The table exist in the database:
custom_2346579543413
custom_5466546513564
they are created by the dialer software and im calling them from another query that provides me the numeric part of the table name so this query loops through the values in customID array to make the query, Thanks again
Update:
Sammitch, thank you for the suggestion, however they did not work.
Solution:
Thanks Marc, you confirmed a suspicion i had in that it was looping correctly but for some reason it was looping more times that there we keys. so i echoed $i to confirm and in fact it was it was outputting 0,1,2,3 and since i know there is only 3 keys the last one didn't return anything and so error handling caught it and killed the entire loop and why it appeared correct when error handling was turned off. The solution was actually rather simple and it was in the while loop evaluation string i had used
while($i<=$numrows)
while($i<$numrows)//this worked, the equals part of that gave it an extra loop
and the query completes as it should.
No, it doesn't. "mysql_fetch_array() expects parameter 1 to be resource" means "the query failed, and you didn't bother to check before calling mysql_fetch_array()".
Your problem is that variable expansion inside of a string doesn't like array indexes. You need to change:
"sum(custom_$customID[$i].d_amt) as sumDamnt,"
To:
"sum(custom_{$customID[$i]}.d_amt) as sumDamnt,"
Or:
"sum(custom_" . $customID[$i] . ".d_amt) as sumDamnt,"
For it to work properly.

Performing a MYSQL query based off of $_GET results

When a user clicks an item on my items page, it takes them to blank page template using $_GET to pass the item brand and model through.
I'd like to perform another MYSQL query when that user clicks through to populate the blank page with the product details from my database. I'd like to retrieve the single row using the model number (unique ID) to populate the page with the information. I've tried a couple of things but am having a little difficulty.
On my blank item page, I have
$brand = $_GET['Brand'];
$modelnumber = $_GET['ModelNumber'];
$query = mysql_query("SELECT * FROM items WHERE `Model Number` = '$modelnumber'");
$results = mysql_fetch_row($query);
echo $results;
I think having ''s around Model Number is causing troubles, but without them, I get a Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given error.
My database columns looks like
Brand | Model Number | Price | Description | Image
A few other things I have tried include
$query = mysql_query("SELECT * FROM item WHERE Model Number = $_GET['ModelNumber']");
Which gave me a syntax error. I've also tried concatenating the $_GET which gives me a mysql_fetch_row() expects parameter 1 to be resource, boolean given error
Which leads me to believe that I'm also going about displaying the results incorrectly. I'm not sure if I need to put it in a where loop like I have with my previous page which displays all items in the database because this is just displaying one.
It seems that your "result" is pulling in too much information for a single variable.
Also, I don't think your table should have column names with spaces, I would suggest filling them all with dashes or underscores.
Here's my suggestion:
$qry = mysql_query("SELECT * FROM items WHERE Model_Number = '$modelnumber'"); //REMEMBER TO MAKE THE CHANGE "Model Number" -> "Model_Number"
while($row = mysql_fetch_array($qry)){
$brand = $row['Brand'];
$modelnumber = $row['Model_Number'];
$price = $row['Price'];
$description = $row['Description'];
$image = $row['Image'];
}
This will populate all of these variables with whatever you have in your tables.
First, notice the first comment on your question. You definitely want to add some sort of sanitation, mysql_real_escape_string at the very least, although PDO or Mysqli would be preferred.
Second, before getting a real answer to your question, let's get some more information about your error.
Try the following:
$brand = mysql_real_escape_string($_GET['Brand']);
$modelnumber = mysql_real_escape_string($_GET['ModelNumber']);
$query = mysql_query("SELECT * FROM items WHERE `Model Number` = '$modelnumber'")OR die(mysql_error());
$results = mysql_fetch_row($query);
var_dump($results);
mysql_error tell us what is going on behind the scenes.
If you are using mysql_fetch_row it will only returns a numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows http://php.net/mysql_fetch_row
If you need to retrieve the data inside that row. You need to use mysql_fetch_array()
also try using mysql_error();
$results = mysql_fetch_row($query) or die(mysql_error());
you will see the error output produce by your code

Returning column names from a mySQL table using PHP

Can't figure this out for the life of me. Trying to return the column names from the clients securities table, then return the result as an array. Can anybody point out where I'm getting off track?
mysql_select_db("HandlerProject", $con); //Selects database
$selectcols = "SELECT * FROM ".$clientname."securitiestable"; //selects all columns from clients security table
$tempcols = mysql_query($selectcols) or die(mysql_error());
$returnedcols = $mysql_fetch_array($tempcols);
$tempsymbol = mysql_query("SHOW COLUMNS FROM".$clientname."securitiestable");
$symbol = $mysql_fetch_array($tempsymbol);
Suggestions:
You've got $ signs prefixing the mysql_fetch_array() calls so you'd need to have assigned a value (function name you want to call) to $mysql_fetch_array (this is probably why you're seeing the error you mention in your comment).
Also you have a missing space after FROM in the second query
// v
$tempsymbol = mysql_query("SHOW COLUMNS FROM ".$clientname."securitiestable");
Last thing to check - is $clientname set?
Having said that - take Bill Karwin's advice!
I would use mysql_fetch_assoc() for the SELECT query, and then call array_keys() on any row of the result.
$selectcols = "SELECT * FROM ".$clientname."securitiestable";
$tempcols = mysql_query($selectcols) or die(mysql_error());
$returnedcols = mysql_fetch_assoc($tempcols);
$colnames = array_keys($returnedcols);
Your fatal error is because of a separate issue: you have a $ symbol at the start of your function call. This is legal PHP syntax, because you can put the name of a function in a variable and call it indirectly:
function foo($arg)
{
echo $arg . "!\n";
}
$bar = "foo";
$bar("hello world");
But in your case, it's probably not what you intended. If you want to call a function by its literal name, don't put a $ in front of it. If you have a string variable that contains the name of a function, then you can use the variable as I show above.

Categories