I am making this for adding storage in an admin section of my site. I have encountered a very strange problem. $voorraad always equals 7, no matter what product I choose(id changes), it keeps coming up as 7.
I am echoing $voorraad by making a session and echoing it in an other page.
The table name and column is correct. Can someone explain why $voorraad always equals seven?
If you need more code, I will provide it.
$cartItems = $cart->contents();
foreach($cartItems as $item){
$sql = ("SELECT voorraad FROM Producten WHERE id =".$item['id']);
$voorraad = (float)mysql_query($sql);
$itm = (float)$item['qty'];
$_SESSION['voorraad'] = $voorraad;
$_SESSION['itm'] = $itm;
$up = $itm + $voorraad;
$sql1 = "UPDATE Producten SET voorraad = $up WHERE id =".$item['id'];
$res = mysql_query($sql1);
}
Because you are converting the mysql response object into a float, you're not actually getting the result.
$voorraad = mysql_query($sql);
$voorraad = mysql_fetch_assoc($voorraad)['voorraad']; // get the row, and the cell from the row
$voorraad should now contain the actual response.
First of all: You are wide open to SQL injection. Filter and validate your user input before passing it to the query.
Second thing: Don't use mysql_*, it's deprecated and considered not safe anymore. Use mysqli_* or PDO instead.
mysql_query() returns a resource, which you try to cast to float. To access the Value(s) you have to use
$result = mysql_query(....);
$row = mysql_fetch_array($result);
$voorraad = $row['voorraad'];
First of all - mysql_*-functions are deprecated and if you update your php version, you couldn't use them anymore. Second, you should use prepared statements, to prevent sql injections.
Back to your main problem:
You execute the query, but you never fetch the result, so you just cast a resource return type to an float, which gives you your unexpected result. In your case, you could use mysql_fetch_assoc to get the row, you want
Because you are converting the mysql response object into a float, you're not actually getting the result.
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$column = $row['column_name'];
Related
For days I've been trying the following: I have a HTML form. After receiving the data (MENGE / PRODUKT / LIEFERANT) I want to insert the data into the table "bestellung". For this purpose, I need two different data points from two different tables: the Waren_ID from the WARE table and the kunde_lieferant_ID from the kunde_lieferant table.
Every time I try this, I get a new error in whatever form (syntax, ...). I've read dozens of Stack Overflow posts, but none helped me out. It would be great if someone could give me a hint :-)
<?php
$server="localhost";
$username="xy";
$passwort="xy";
$database="xy";
$conn=mysqli_connect($server, $username, $passwort, $database)
or die ("Fehler im System");
if (!empty($_POST["Lieferant"]) AND !empty ($_POST["Produkt"]) AND !empty ($_POST["Menge"]))
{
$Menge = $_POST ["Menge"];
$Produkt = $_POST["Produkt"];
$Lieferant = $_POST ["Lieferant"];
$sql="SELECT Waren_ID FROM ware WHERE Name='$Produkt'";
$speichern = mysqli_query($conn, $sql);
$rs = mysqli_fetch_array($speichern);
$Waren_ID=$rs['Waren_ID'];
$abfrage="SELECT kunde_lieferant_ID FROM kunde_lieferant WHERE Name='$Lieferant'";
$result = mysqli_query($conn, $abfrage);
$ts = mysqli_fetch_array($result);
$kunde_lieferant_ID=$ts['kunde_lieferant_ID'];
$final="INSERT INTO bestellung (Menge, Waren_ID, kunde_lieferant_ID) values ($Menge, $Waren_ID, $kunde_lieferant_ID)";
$ende=mysqli_query($conn, $final)
or die ("Fehlgeschlagen: SQL-Error:" . mysqli_error($conn));
}
mysqli_close($conn);
?>
Add MYSQLI_ASSOC as a second argument to mysqli_fetch_array() to use the key name instead of the integer index number:
$rs = mysqli_fetch_array($speichern); becomes $rs = mysqli_fetch_array($speichern, MYSQLI_ASSOC);
and
$ts = mysqli_fetch_array($result); becomes $ts = mysqli_fetch_array($result, MYSQLI_ASSOC);
You may also use $rs = mysqli_fetch_assoc($speichern); and $rs = mysqli_fetch_assoc($speichern); to access the associative array by key name instead of index.
One potential problem in your insert statement is that you are not single-quoting the values that your are passing : to MySQL, this means that they are all numeric (but is « Menge » numeric for example ?).
To avoid this and also prevent your code from SQL injection, you probably should use parameterized queries.
By looking more globally at your code, I think that you should be able to achieve what you want in a single INSERT ...SELECT statement, like :
INSERT INTO bestellung
SELECT
:menge,
w.Waren_ID,
k.kunde_lieferant_ID
FROM
ware w
INNER JOIN kunde_lieferant k
ON k.Name = :lieferant
WHERE w.Name = :produkt
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
I have an SQL query as follows:
$tagID = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
echo $tagID;
I want $tagID to contain something like 3, or 5, or any integer. But when I echo it, the output is:
resource id #4
How can I make it a simple integer?
$result = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'"); // figure out why an existing tag gets the ID zero instead of 'tagID'
$row = mysql_fetch_assoc($result);
echo $row["tagID"];
mysql_query() returns result resource, not the value in the query. You have to use fetch functions to get the actual data.
If you want this code to be cleaner, check that $result is not false (query error) and $row is not false (nothing found).
It's always a shock to see not a single programmer in the answers.
I know the OP is not a programmer too, so, my answer would be totally in vain but what the heck.
Here is a example of a thing called a function:
<?
function dbgetvar(){
$args = func_get_args();
$query = array_shift($args);
foreach ($args as $key => $val) {
$args[$key] = "'".mysql_real_escape_string($val)."'";
}
$query = vsprintf($query, $args);
$res = mysql_query($query);
if (!$res) {
trigger_error("dbgetarr: ".mysql_error()." in ".$query);
return FALSE;
} else {
$row = mysql_fetch_row($res);
if (!$row) return NULL;
return $row[0];
}
}
this code can be saved in some configuration file and then called in this manner:
$tagID = dbgetvar("SELECT tagID FROM tags WHERE tagName = %s",$tag);
echo $tagID;
The mysql_query function, by itself, returns a 'resource' on success and false on error. In this case, you're getting a resource that has id #44, which is what you might expect from that function.
What you could do is take the result of mysql_query and use mysql_fetch_assoc to convert the resource to an associative array. (Also check out mysql_fetch_row, or mysql_fetch_field for other techniques). Here's a typical way of structuring this problem:
$query = "SELECT tagID FROM tags WHERE tagName = '$tag'";
$result = mysql_query($query);
$array = mysql_fetch_assoc($result);
$tagID = $array['tagID']; //your integer.
Please see the mysql_query PHP Manual entry for more info. Check out the user comments at the bottom for particularly good advice and sample code.
You're missing a single step. Try this:
$resource = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
$tagID = mysql_fetch_assoc($resource);
print_r($tag_id);
If your query returns more than one row (i.e. there is more than one tag with the same tagName), you'll want to put it in a loop:
$resource = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
while($tagID = mysql_fetch_assoc($resource)) {
echo $tagID['tagID'];
}
Addendum
Although the above code will solve your problem, I urge you to stop right there and learn about mysqli instead. It's a much newer, more robust solution than using the mysql_* functions. From the docs:
The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer. The mysqli extension is included with PHP versions 5 and later.
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:
Object-oriented interface
Support for Prepared Statements
Support for Multiple Statements
Support for Transactions
Enhanced debugging capabilities
Embedded server support
Also from the docs:
If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use [the MySQLi] extension.
A SQL query always returns a SQL Resource result, an arguably unreadable object that contains the results of the query. Because of the way that databases are stored, the way that users may want to manipulate data, and the sheer amount of data, it's easier to store it as an identifier than as an object.
To get the data, you need, you must first convert it to an array:
$result = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
$row = mysql_fetch_assoc($result);
echo $row["tagID"];
(Where $row[column] is the column you want to pull data from(
Or an object:
$result = mysql_query("SELECT tagID FROM tags WHERE tagName = '$tag'");
$object = mysql_fetch_object($result);
echo $object->tagID;
(where $object->column is the column you want to pull data from)
Hope this helps.
I have a PHP server script that SELECTs some data from a MySQL database.
As soon as I have the result from mysql_query and mysql_fetch_assoc stored in my own local variables, I want to delete the row I just selected.
The problem with this approach is that it seems that PHP has done pass-by-reference to my local variables instead of pass-by-value, and my local variables become undefined after the delete command.
Is there anyway to get around this? Here is my code:
$query="SELECT id, peerID, name FROM names WHERE peer = $userID AND docID = '$docID' AND seqNo = $nid";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:1 getUsersNamesUpdate() query: ".$query."\n");
if (mysql_num_rows($result) == 0)
return array();
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:2 getUsersNamesUpdate() query: ".$query."\n");
return $result;
You are overwriting your $result variable with your second statement:
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query); // result does not contain the array anymore
Change the name to something else. It has nothing to do with call-by-reference or such.
Actually, your first assignment of the values is unnecessary as $row is already an array:
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
You could just do:
$row = mysql_fetch_assoc($result);
// at the end
return $row;
Then you don't even have to change your variable name for the second statement. But consider to use meaningful variable names.
First of all, why not just use only one query to delete the row that interests you ?
Something like this should do the trick, I suppose :
delete
from names
where peer = $userID
AND docID = '$docID'
AND seqNo = $nid
Of course, don't forget to escape/convert the values that should be ;-)
This way, no need for a select query, followed by a delete one.
Second : to make your code more easier to read / understand / maintain, you should probably not re-use the same variable for several different purposes.
Here, your $result variable is used for more than one thing, and it makes things harder to understand :
resource returned by the first mysql_query
then, array containing data from the first row
then, resource returned by the second mysql_query
It's a bit confusing, and will, one day or another, lead to errors...
Actually, it already has ;-) : the third assignment is overriding the data you're getting with the second ones, and boom, you've lost the information that corresponds to the row you've just deleted ;-)
I'm using PHP ADOdb and I can get the result set:
$result = &$db->Execute($query);
How do I get the field names from that one row and loop through it?
(I'm using access database if that matters.)
It will depend on your fetch mode - if you setFetchMode to ADODB_FETCH_NUM (probably the default) each row contains a flat array of columns. If you setFetchMode to ADODB_FETCH_ASSOC you get an associative array where you can access each value by a key. The following is taken from ADODB documentation - http://phplens.com/lens/adodb/docs-adodb.htm#ex1
$db->SetFetchMode(ADODB_FETCH_NUM);
$rs1 = $db->Execute('select * from table');
$db->SetFetchMode(ADODB_FETCH_ASSOC);
$rs2 = $db->Execute('select * from table');
print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
To loop through a set of results:
$result = &$db->Execute($query);
foreach ($result as $row) {
print_r($row);
}
Small improvement to the solution posted by #thetaiko.
If you are ONLY needing the field names, append LIMIT 1 to the end of your select statement (as shown below). This will tell the server to send you a single row with column names, rather than sending you the entire table.
SELECT * FROM table LIMIT 1;
I'm working with a table that contains 9.1M records, so this minor change speeds up the query significantly!
This is a function I use to return a field array - I've stripped out some extra stuff that, for example, allows it to work with other DBs than MySQL.
function getFieldNames($strTable, $cn) {
$aRet = array();
# Get Field Names:
$lngCountFields = 0;
$strSQL = "SELECT * FROM $strTable LIMIT 1;";
$rs = $cn->Execute($strSQL)
or die("Error in query: \n$strSQL\n" . $cn->ErrorMsg());
if (!$rs->EOF) {
for ($i = 0; $i < $rs->FieldCount(); $i++) {
$fld = $rs->FetchField($i);
$aRet[$lngCountFields] = $fld->name;
$lngCountFields++;
}
}
$rs->Close();
$rs = null;
return $aRet;
}
Edit: just to point out that, as I say, I've stripped out some extra stuff, and the EOF check is therefore no longer necessary in the above, reduced version.
I initally tried to use MetaColumnNames, but it gave differing results in VisualPHPUnit and actual site, while running from the same server, so eventually
I ended up doing something like this:
$sql = "select column_name, column_key, column_default, data_type, table_name, table_schema from information_schema.columns";
$sql .= ' where table_name="'.$table.'" and table_schema="'.$database_name.'"';
$result = $conn->Execute($sql);
while($row = $result->fetchRow()) {
$out[] = strToUpper($row['column_name']);
}
I think it should work with mysql, mssql and postgres.
The benefit of doing it like this, is that you can get the column names, even if a query from a table returns an empty set.
If you need the Coloumn names even for empty tables or for joins about multiple tables use this:
$db->Execute("SELECT .......");
// FieldTypesArray - Reads ColoumnInfo from Result, even for Joins
$colInfo = $res->FieldTypesArray();
$colNames = array();
foreach($colInfo as $info) $colNames[] = $info->name;
The OP is asking for a list of fieldnames that would result of executing an sql statement stored in $query.
Using $result->fetchRow(), even with fetch mode set to associative, will return nothing if no records match the criteria set by $query. The $result->fields array would also be empty and would give no information for getting the fieldnames list.
Actually, we don't know what's inside the $query statement. Besides, setting limit to 1 may not compatible with all database drivers supported by PHP ADOdb.
Answer by Radon8472 is the right one, but the correct code could be:
$result = $db->Execute($query);
// FieldTypesArray - an array of ADOFieldObject Objects
// read from $result, even for empty sets or when
// using * as field list.
$colInfo = [];
if (is_subclass_of($result, 'ADORecordSet')){
foreach ($result->FieldTypesArray() as $info) {
$colInfo[] = $info->name;
}
}
I have the habit of checking the class name of $result, for as PHP ADOdb will return false if execution fails.