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
Related
I'm working on a Kitchen Display Screen. I have it working if I know the order numbers. I'm trying to get all of the order numbers where status = "INQUEUE" and put those numbers into an array. The goal is to have a count of the total "INQUEUE" orders as well as have the segments on the screen only show arr[0]-Arr[4]. For some reason this section of code causes an error.
$status= "INQUEUE";
$arr = array();
$sql = "select ORDID from HEADERS where CurrentStatus=$status";
$result = mysql_query($sql) or die(mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
$arr[] = $row[ORDID];
}
I'm hoping to grab all of the order numbers that have a status of "INQUEUE" into the array, so I can display the orders as arr[X]
What is the specific error you are receiving?
One thing that stands out on the query is the variable needs to be enclosed within single quotes so it looks like this:
$sql = "select ORDID from HEADERS where CurrentStatus='$status'";
Sometimes when I'm working with dynamically-built queries I like to echo out the query string so I can see exactly how it's being sent to the server.
Also, it's always a good idea to get in the habit of using prepared statements with parameterized queries when working with dynamically-built SQL queries.
Also, in agreement with ArtisticPhoenix, I recommend porting over to another library. Finally, make sure the array index descriptor is enclosed in double quotes. Here's your code using mysqli:
$link = mysqli_connect("dbserver", "user", "password", "database");
$status= "INQUEUE";
$arr = array();
$sql = "select ORDID from HEADERS where CurrentStatus='$status'";
$result = mysqli_query($link, $sql);
while( $row = mysqli_fetch_assoc($result)) {
$arr[] = $row["ORDID"];
}
I have a database with users input and was wanting to output a user table (id, username) as a count on a page. The following piece of code is what I've been trying to work with but I've been having no luck and it keeps getting more and more complex - the SQL works perfectly so I'm not sure what's wrong.
mysqli_select_db($db);
$result = $_POST ['$result'] ;
$result = mysqli_query("SELECT COUNT( * )
FROM users");
$row = mysqli_real_escape_string($result,$db);
$total = $row[0];
echo "Total rows: " . $total;
I'm still learning how to properly link SQL in with PHP. The warnings tell me to add an extra parameter however when I do so it still complains.
I originally wanted a simple COUNT but will change the count to a table array if need be. I understand this maybe a little basic and I may have been going about it the wrong way, but I've hit a wall with it and any help on fixing the COUNT would be greatly appreciated
Replace the call to mysqli_real_escape_string to mysqli_fetch_array and your code will works.
mysqli_real_escape_string is only useful for string escaping when you INSERT or UPDATE data to MySQL.
$row = mysqli_fetch_array ($result);
Please try this code:
$sql="SELECT * FROM users";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
$number = count($rows);
Hope this works.
I'm using Postgresql 9.2 and PHP 5.5 on Linux. I have a database with "patient" records in it, and I'm displaying the records on a web page. That works fine, but now I need to add interactive filters so it will display only certain types of records depending on what filters the user engages, something like having 10 checkboxes from which I build an ad-hoc WHERE clause based off of that information and then rerun the query in realtime. I'm a bit unclear how to do that.
How would one approach this using PHP?
All you need to do is recieve all the data of your user's selected filters with $_POST or $_GET and then make a small function with a loop to concatenate everything the way your query needs it.
Something like this... IN THE CASE you have only ONE field in your DB to match with. It's a simple scenario and with more fields you'll need to make it so that you add the field you really need in each case, nothing too complex.
<?php
//recieve all the filters and save them in array
$keys[] = isset($_POST['filter1'])?'$_POST['filter1']':''; //this sends empty if the filter is not set.
$keys[] = isset($_POST['filter2'])?'$_POST['filter2']':'';
$keys[] = isset($_POST['filter3'])?'$_POST['filter3']':'';
//Go through the array and concatenate the string you need. Of course, you might need AND instead of OR, depending on what your needs are.
foreach ($keys as $id => $value) {
if($id > 0){
$filters.=" OR ";
}
$filters.=" your_field = '".$value."' ";
}
//at this point $filters has a string with all your
//Then make the connection and send the query. Notice how the select concatenates the $filters variable
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM table WHERE ".$filters;
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_row($rs)) {
echo "$row[0] $row[1] $row[2]\n";
//or whatever way you want to print it...
}
pg_close($con);
?>
The above code will get variables from a form that sent 3 variables (assuming all of them correspond to the SAME field in your DB, and makes a string to use as your WHERE clause.
If you have more than one field of your db to filter through, all you need to do is be careful on how you match the user input with your fields.
NOTE: I did not add it here for practical reasons... but please, please sanitize user input.. ALWAYS sanitize user input before using user controlled data in your queries.
Good luck.
Don't do string concatenation. Once you have the values just pass them to the constant query string:
$query = "
select a, b
from patient
where
($x is not null and x = $x)
or
('$y' != '' and y = '$y')
";
If the value was not informed by the user pass it as null or empty. In the above query the x = $x condition will be ignored if $x is null and the y = '$y' condition will be ignored if $y is empty.
With that said, a check box will always be either true or false. What is the exact problem you are facing?
Always sanitize the user input or use a driver to do it for you!
I have created a Where clause builder exactly for that purpose. It comes with the Pomm project but you can use it stand alone.
<?php
$where = Pomm\Query\Where::create("birthdate > ?", array($date->format('Y-m-d')))
->andWhere('gender = ?', array('M'));
$where2 = Pomm\Query\Where::createWhereIn('something_id', array(1, 15, 43, 104))
->orWhere($where);
$sql = sprintf("SELECT * FROM my_table WHERE %s", $where2);
$statement = $pdo->prepare($sql);
$statement->bind($where2->getValues());
$results = $statement->execute();
This way, your values are escaped and you can build dynamically your where clause. You will find more information in Pomm's documentation.
I have a table with 4 columns and 23 rows. I need all 92 values in the the table as PHP variables (whether that be one array, 4 arrays, 92 individual variables, or whatever).
The rows are:
ID
Category
Summary
Text
I need to build a series of select boxes where the items are grouped by the category, the options available are the summaries, and the resulting text is passed on for processing.
I've been searching, but all the examples I can find are about printing the table out, and I need to continue working with the variables.
I really appreciate any help!
Billy
Just a SELECT * FROM table_name will select all the columns and rows.
$query = "SELECT * FROM table_name";
$result = mysql_query($query);
$num = mysql_num_rows($results);
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
// You have $row['ID'], $row['Category'], $row['Summary'], $row['Text']
}
}
OK, I found my answer with better search terms. I'm still new here, so let me know if this is not a fair way to handle the situation. I upvoted #Indranil since he or she spent so much time trying to help me.
Anyway...
$content = array();
while($row = mysql_fetch_assoc($result)) {
$content[$row['id']] = $row;
}
Puts my whole entire table into one huge, multidimensional array so that I can use it throughout my code. And it even names the first level of the array by the ID (which is the unique identifier).
Thank you to those that tried to help me!
Billy
$pdo = new PDO(
'mysql:host=hostname;dbname=database;charset=utf-8',
'username',
'password'
);
$pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
$stmt = $pdo->query('SELECT ID, Category, Summary, Text FROM Table');
if ( $stmt !== false )
{
$data = $stmt->fetchAll( PDO::FETCH_ASSOC );
}
In the case if the SQL query has no conditions, use query() , otherwise, you should be using prepare() ans bind the parameters.
Oh .. and please stop using the ancient mysql_* functions, they are in the process of being deprecated and no new code should written with them.
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 ;-)