I'm trying to update a mySQL table using php. Basically I pass an ordernumber (int) and use it to find both isbn and quantityordered which I then use to update another table.
$orderID=$_POST["order_ent_number"];
$query="select ISBN from Orders where orderNumber='$orderID'";
$isbn = mysql_query($query) or die(mysql_error());
$query="select quantityOrdered from Orders where orderNumber='$orderID'";
$quantityordered = mysql_query($query) or die(mysql_error());
$query="UPDATE Books SET inStock='$quantityordered' WHERE inStock='0' AND isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
So using the MySQL bench, the query works (if I replace all variables with numbers) and changes it. The problem is when I use the variables in PHP, the code does not work. I tried the mysql_escape_string but that didnt work either. I checked the results of both variables $isbn and $quantityordered and they are right. I get no errors when I run it on the server but there is no change to inStock in the database. After searching around, someone said my variables need to be turned into integers? Not sure if this is correct or not but that is all I came up with. Any suggestions?
Actually you can do it in a single UPDATE statement by joining the tables,
UPDATE Books a
INNER JOIN Orders b
ON a.ISBN = b.ISBN
SET a.instock = a.quantityOrdered
WHERE a.instock = 0 AND
b.OrderNUmber = '$orderID' AND
a.ISBN = '$isbn'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
maybe you can try
$query="select ISBN from Orders where orderNumber='".$orderID."'";
$query="select quantityOrdered from Orders where orderNumber='".$orderID."'";
$query="UPDATE Books SET inStock='".$quantityordered."' WHERE inStock='0' AND isbn='".$isbn."'";
Related
I want to compare a stored DateTime entry in my Database with the current date using Doctrine.
I have a list of Keys and their relation to a Person. My goal now is to create a list for available keys or not available keys.
For that I have to look at 2 Tables, key and personToKey. Where personToKey has a field rueckgabe(time to return the key) (dateTime) and a field key (stored id of the key) with an OneToMany Relation to the field id of the Table key.
Thanks to some search here, I got a running SQL Query which gives me the values I am looking for.
SQL Query:
SELECT * FROM key LEFT OUTER JOIN personToKey on key.id = personToKey.KeyId
WHERE personToKey.rueckgabe < NOW()
My Problem is now, that I don't get this to work using doctrine. I had 2 approaches for this.
$qb = $em->createQueryBuilder();
$query = $qb->select('k')
->from('MyBundle:key', 'k')
->leftjoin('MyBundle:personToKey', 'ptk','WITH', 's.id = ptk.key')
->where('ptk.rueckgabe < :date_now')
->setParameter('date_now', date('Y-m-d H:i:m'))
->getQuery();
$test = $query->getResult();
And
$sql = 'SELECT k FROM MyBundle:key k LEFT OUTER JOIN MyBundle:PersonToKey ptk WITH k.id = ptk.key WHERE ( ptk.rueckgabe < CURRENT_DATE()) ';
$query = $em->createQuery($sql);
$test = $query->getResult();
Since the SQL Query works I would have thought that at least the second approach should have worked. But in both cases I get the following results:
for ptk.rueckgabe >= :date_now the list is fine, but for ptk.rueckgabe < :date_now I get a mix of available and not available keys. Also the length of the result is below the number of rows the SQL Query finds in PHPMyAdmin.
Thanks in advance.
As the answer here states:
The equivalent of MySQL's NOW() is Doctrine DQL's CURRENT_TIMESTAMP().
CURRENT_DATE() only returns the date part.
This might explain, why the second approach did not give the same result as running a straight SQL query.
For the first approach you could try the following, even though I am not sure if it will make a difference:
->setParameter('date_now', new \DateTime())
Edit:
I found another potential problem in your QueryBuilder:
Instead of
->leftjoin('MyBundle:personToKey', 'ptk','WITH', 's.id = ptk.key')
you could try to write:
->leftjoin('k.personToKey', 'ptk')
The s.id was definitely wrong, not sure about the rest.
I finally found a working solution for my Problem, so I wanted to share it, if other People have a similar problem.
$now = new \DateTime() ;
$now1=$now->format('Y-m-d H:i:s');
$sql = 'SELECT * FROM key AS k
LEFT OUTER JOIN persontoKey AS ptk ON k.id = ptk.keyId
WHERE ( ptk.rueckgabe < :now ) ';
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->bindValue('now', $now1, \PDO::PARAM_STR);
$stmt->execute();
$helper= $stmt->fetchAll();
I was happy when I got this to work but it submits the order twice unless I comment out the last two lines. Is there a better way to write it so that I don't get duplicates?
$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$conn->query($sql);
$recordid = $conn->insert_id;
I did this this way because I'm trying to use the record ID as the order ID. I echo this order ID back to the customer on the purchase receipt.
updated code:
$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$recordid = mysql_insert_id();
no duplicates, but does not return the record ID.
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future.
Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more information.
Alternatives to this function include:
mysqli_insert_id()
PDO::lastInsertId()
Try the following:
$sql = "INSERT INTO orders (weight, shipper, shipacct) VALUES ('$weight', '$shipper', '$shipacct')";
$conn->query($sql);
$recordid = mysql_insert_id();
Note:
Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
Hopefully, this and this will help...
I have a problem with symfony2 record insertion
My requirement is to find out all the users who are in between particular ages and the given column is dob.
I am getting the result with this mysql query.
SELECT * FROM app_users WHERE YEAR(CURDATE())-YEAR(dob) BETWEEN 10 AND 20;
How to rewrite this query in the symfony- doctrine fromat?
Pls help...
$qb = $em->createQueryBuilder();
$qb->select('au')
->from('AppUsers au)
->where($qb->expr()->between('YEAR(CURDATE())-YEAR(au.dob)', 10,20));
$result = $qb->getQuery()->getResult();
I have not checked it. but it may help you.
Consider following two tables:
tag_names (tag_id, tag_name)
tag_links (tag_id, image_id)
An image can have multiple tags, I want to select all tags for a specific image id.
I am trying following query, but it doesnt seem to select correctly (selects only one row), What is wrong with it?
SELECT tag_name
FROM tag_names
LEFT JOIN tag_links.tag_id = tag_names.tag_id
WHERE tag_links.image_id = $image_id
Edit: I'm using CodeIgniter Active record query, but I wrote in basic SQL format so that if someone is not fimiliar with CodeIgniter can help. However, this query works fine with simple mysql format (without using CodeIgniter) but strangely does not work with CodeIgniter, even there is no any problem with the syntax, it just selects one row.
Here is CodeIgniter Syntax:
$this->db->select('tag_name');
$this->db->from('tag_names');
$this->db->join('tag_links', 'tag_links.tag_id = tag_names.tag_id', 'left');
$this -> db -> where('tag_links.image_id', (int)$image_id);
$query = $this->db->get();
Try this:
SELECT tag_name
FROM tag_names
LEFT JOIN tag_links
ON tag_links.tag_id = tag_names.tag_id
WHERE tag_links.image_id = $image_id
IMHO you forgot to join table (properly with ON statement) you are using.
EDIT: I have 2 ideas how to get rid of the problem:
First:
Change the line with SELECT
$this->db->select('tag_names.tag_name');
Second:
Use select() function with complete query:
$this->db->select($query, false);
$this->db->select() accepts an optional second parameter. If you set
it to FALSE, CodeIgniter will not try to protect your field or table
names with backticks. This is useful if you need a compound select
statement.
from: http://codeigniter.com/user_guide/database/active_record.html#select
It seems that you have a syntax error (you forgot tag_links in JOIN clause). By the way in my opinion you don't need LEFT JOIN for this purpose otherwise you may get incorrect results.
SELECT tag_name
FROM
tag_names
JOIN tag_links ON tag_links.tag_id = tag_names.tag_id
WHERE tag_links.image_id = $image_id
SELECT tag_names.tag_name
FROM tag_links
LEFT JOIN tag_names.tag_id = tag_links.tag_id
WHERE tag_links.image_id = $image_id
tag_names is only going to have single entry for a given ID, which means your query will return a single result. You need to primarily select from tag_links and then join the name of the tag on top of it, so you correctly select from the table with the multiple entries.
$result = mysql_query("SELECT * FROM Volunteers WHERE Volunteers.eventID = " . $var);
$sql = mysql_query("SELECT * FROM Members WHERE Members.pid = " . $temp);
I am also doing or die(mysql_error()) at the end of both statements if that matter. My problem is that the first statement executes perfectly but in that table I store an attribute called pid. So the second statement is supposed to take that and return the row where it equals that pid so I can get the name. I get an error that says unknown column in 'a2' in 'where clause' where a2 the pid attribute returned from the first statement. Thanks for any help!
EDIT: Figured out what was wrong.
Had to write the code like this:
$sql = mysql_query("SELECT * FROM Members WHERE Members.pid = '$temp'") or die(mysql_error());
I think I see what you are trying to do, you can do this in one query, by JOIN-ing the tables together. the SQL query should be something like
SELECT Members.* FROM Members INNER JOIN Volunteers ON Volunteers.eventID=Members.pid WHERE Volunteers.eventID=" . $var
Check out This for a basic introduction to SQL joins.