I have the following MySqli query:
$run = 0;
$result = $conn->query("SELECT title, author,i.isbn13, i.sku, quantity, weight, listed_price
from book
LEFT JOIN inventory i on book.isbn13 = i.isbn13
where quantity > 0 and i.isbn13 like '978%' limit $run, 5");
Which I then run through Amazon's API to return XML Data. I then parse that to update my table with:
$conn->query("update book set author = '" . addslashes($amazonResult['Author']) . "', title ='" . addslashes($amazonResult['Title']) . "',
edition='" . addslashes($amazonResult['Edition']) . "',
weight='" . $amazonResult['Weight'] . "', publisher='" . addslashes($amazonResult['Publisher']) . "', binding='" . $amazonResult['Binding'] . "',
pub_date='" . $amazonResult['PublishDate'] . "', listed_price = '" .$amazonResult['ListPrice'] . "'
where isbn13 = '" . $amazonResult['isbn'] . "'");
Update $run:
$run=$run+5;
and have it loop through again. Yet my output skips the first 5 rows in the table and returns the next 5. Also, after running about 20 or so records, it skips 5 again. The rows that it processes, it does correctly, which I verify by an echo of the query. When I use the query in Navicat, replace $run with 0, everything looks fine, the first 5 rows are returned.
Any idea what I did wrong or how I can fix this? I have never encountered this in the past and use almost the same query for different reports.
If you want to return a specific range of records, make sure to also add an order by clause. MySQL might change the order of rows between queries.
Another, maybe even more plausible cause, is that a query can sometimes fail. For instance, if one of the fields contains an invalid character, it might break your query, return false instead of a mysqli query result, and therefor fail to output anything.
You are using addslashes to escape strings, but that's not the proper way to do it. You can use mysqli_real_escape_string, or even better: use parameterized queries (prepared statements).
Related
My problem is that i don't yet have a good server to test this on but i'd like to know if it faster to use:
$sqlgetg = "SELECT assignments.id FROM assignments LEFT JOIN userassignments ON assignments.id = userassignments.assignmentid WHERE userassignments.userid = '" . $row['id'] . "' AND userassignments.assignmentid = '" . $assignmentid . "'";
or
$sqlgetg = "SELECT NULL FROM assignments LEFT JOIN userassignments ON assignments.id = userassignments.assignmentid WHERE userassignments.userid = '" . $row['id'] . "' AND userassignments.assignmentid = '" . $assignmentid . "'";
Since i have to check if there even is an assigment for the user with assignment id of x? I don't need anything else but this: if(mysqli_num_rows($resultgetg) > 0)? In both cases phpMyAdmin gave me the row number that i wanted. (I checked it with
without WHERE and it still worked.)
EDIT:
I don't know how and why NULL works but it does...
You can select any static value "from" a table if you just want to count the rows returned... SELECT NULL or SELECT 42 or whatever. But both of your strategies are in fact suboptimal, because they require unnecessary work by the server and unnecessary network traffic and unnecessary handling of the result set that you are only planning to discard.
If counting rows is what you want, then actually do that. you should SELECT COUNT(*) AS how_many_rows ... and let the server count the rows and return a single row with a single column ("how_many_rows" -- make up your own alias) containing the count.
I'm trying to print out only the number of rows containing user2_ids within my streamdata_feedback table and it seems to be printing out both the user2_id and the user1_id. How can I rectify this issue with the below code?
$user1_id=$_SESSION['id'];
$user2_id=$data['id'];
$likesqltwo = "SELECT *
FROM streamdata_feedback
WHERE feedback_rating = 1
AND feedback_userid = " . $user2_id .
"AND feedback_streamid = " . $streamid;
$likequerytwo = mysql_query($likesqltwo);
$num3 = mysql_num_rows($likequerytwo);
if ($num3 > 0)
{
echo "And <a title = 'See who likes " .
$poster_name['fullusersname'] .
"s status' href='include/likes.php?streamitem_id=" .
$streamitem_data['streamitem_id']."' />" .
$num3 . " ";
}
Do you have a client for your MySQL database? I'd recommend picking up SqlYog Community Edition. You can then execute your query against it and see how many rows are returned outside of PHP code. Once you have a satisfactory query, then incorporate it into your PHP project.
Next tip: You can include variables from PHP directly in strings with double quotes. PHP will parse the variable, and you needn't concatenate. For example:
$likesqltwo =
"SELECT *
FROM streamdata_feedback
WHERE feedback_rating = 1
AND feedback_userid = $user2_id
AND feedback_streamid = $streamid;";
However this code still has a potential flaw, and that's SQL injection attacks. So ensure that the variables you include are not coming from users, or follow the link to learn more about preventing such things. That's not what you asked for help on, but I thought it was worth a mention.
To find out how many times the feedback_userid equals $user2_id for a particular feedback_streamid and for only feedback_rating values of 1, you could try the following query:
SELECT COUNT(id)
FROM streamdata_feedback
WHERE feedback_rating = 1
AND feedback_userid = 123
AND feedback_streamid = 456;
Substitute your primary key for id, and the correct user id and stream id for 123 and 456 respectively. If you get an unexpected number of results, I recommend removing COUNT(id) and selecting the columns of interest so you can inspect and see why you're getting more rows than you thought.
I'm trying to code a tooltip, which uses http://craigsworks.com/projects/simpletip/# simpletip plugin, which returns data via ajax. However, i can't seem to display the data from 3 tables, which is fetched via the data image, as each image is assigned to it's own id. as seen below, i need to display all data from the table, but with 3 tables to read from. in my webpage, a php statement will query data from one table for each category, generated by this tooltips. only a round tooltip came out, not even mysql_error(). i need help asap. this is the only site where i seem to get inputs from others.
<?php
define('INCLUDE_CHECK', 1);
require "../connect.php";
if (!$_POST['img'])
die(mysql_error());
$img = mysql_real_escape_string(end(explode('/', $_POST['img'])));
$row = mysql_fetch_assoc(mysql_query("SELECT alcoholic.*, non_alcoholic.*,
non_alcoholic1.* FROM alcoholic INNER JOIN non_alcoholic USING (img) INNER JOIN
non_alcoholic1 USING (img) WHERE img='" . $img . "' "));
if (!$row)
die(mysql_error());
echo '<strong>' . $row['name'] . '</strong>
<p class="descr">' . $row['description'] . '</p>
<strong>price: $' . $row['price'] . '</strong>
<small>Drag it to your shopping<br /> cart to purchase it</small>';
?>
I'm guessing there are three tables with an img column? If so, is this what you need?:
SELECT
alcoholic.*, non_alcoholic.*, non_alcoholic1.*
FROM
alcoholic
INNER JOIN non_alcoholic USING (img)
INNER JOIN non_alcoholic1 USING (img)
WHERE
img = '" . $img . "'
Edit: When I said update your OP with the new issue I didn't mean overwrite it, I meant add it underneath so that this answer (and others if there were any) make sense.
Anyway, the problem is that $row['name'], etc. don't refer to anything in the SELECT statement. You need to change alcoholic.*, non_alcoholic.*, non_alcoholic1.* to what it is you're pulling out, for example:
SELECT alcoholic.name, alcoholic.description, alcoholic.price ...
.Hi guys, i need a little help with a project that i'm currently working on.
I have this database where i have a table containing records of students from different departments namely:
Dept1
Dept2
Dept3
Dept4
Dept5
in my batch.php i have two dropdown menus for Batch(which is the name of the tables) and Department(a field used for sorting).
what i want to do is that when the user chooses a Batch and a Department and then clicks the submit button, it will automatically assign the values chosen to a MySQL query for the SELECT method. the SELECT query should now retrieve all records from the table sort it by department but will display first the Department that was chosen above.
.Any help would be much appreciated. Thanks in advance and more power!
You can sort by a boolean expression, which will return 1 when true and 0 when false.
<?php
$batch = mysql_real_escape_string($_POST['batch']);
$department = mysql_real_escape_string($_POST['department']);
$query = "SELECT * FROM `" . $batch . "`" .
" WHERE department = '" . $department . "'" .
" ORDER BY department = '" . $department . "' DESC, department;
?>
Update: You should validate the $batch argument that it is a valid table expected, the code as is is vulnerable to SQL injection.
I have 6 select items in a form. I want to search those 6 in MYSQL DB. I can retrieve results if I use only one, like:
$result = mysql_query("SELECT * FROM wsinmuebles WHERE Property_Type LIKE '%{$_POST['Property_Type']}%'");
But when I try more, I get no results!
$result = mysql_query("SELECT * FROM wsinmuebles WHERE
Property_Type LIKE '%{$_POST['Property_Type']}%' AND
Estado LIKE '%{$_POST['Estado']}%' AND
Ciudad LIKE '%{$_POST['Ciudad']}%' AND
Urbanizacion LIKE '%{$_POST['Urbanizacion']}%' AND
Operacion LIKE '%{$_POST['Operacion']}%' AND
Precio_bsf LIKE '%{$_POST['Precio_bsf']}%'");
This comes from a form by the POST method.
What I need is to look for Property_Type, Estado, Ciudad, Urbanizacion, Operacion and Precio_bsf variables in MYSQL DB, and receive only the results that match all those values.
First, escape the post values using mysql_real_escape_string (Link) to avoid any SQL injection attacks and also issues with the data having ' characters.
Second echo the query and run it against the database and check the table data to see if the
query indeed should return some values or may be there are no matches when include the rest of criteria since you mentioned that you are expecting the results that match all those values.
Dont use And use Or between criteria, and after all you should know that concatenating strings and executing queries is giving possible SQL Injection, that is when instead of your search string I end your query and execute given action, for example "' and 1=1; delete wsinmuebles" if this is my serach query you will lose all your data.
$result = mysql_query("select * from tbl1 where Name='".mysql_escape_string ($_POST["value"]."'" );
If a field, say Urbanizacion is null, your query will not return it.
Urbanizacion LIKE '%%' => FALSE when Urbanizacion is Null
You will need to handle Nulls. I also strongly urge you to protect the code from SQL Injection using mysql_real_escape_string
$result = mysql_query("
SELECT * FROM wsinmuebles WHERE
IFNULL(Property_Type,'') LIKE '" . mysql_real_escape_string($_POST['Property_Type']) ."' AND
IFNULL(Estado,'') LIKE '" . mysql_real_escape_string($_POST['Estado']). "' AND
IFNULL(Ciudad,'') LIKE '" . mysql_real_escape_string($_POST['Ciudad']) ."' AND
IFNULL(Urbanizacion,'') LIKE '" . mysql_real_escape_string($_POST['Urbanizacion']) ."' AND
IFNULL(Operacion,'') LIKE '" . mysql_real_escape_string($_POST['Operacion']) ."' AND
IFNULL(Precio_bsf,'') LIKE '" . mysql_real_escape_string($_POST['Precio_bsf']) ."'");