simple MySQL query via PHP - php

I have a table with about 500,000 rows, and need to query it to retrieve results. Basically the user just inputs a case number, and then I want to execute the following query and display the results using a while loop
if (!empty($_POST["casenum"])) {
$result2 = mysql_query("SELECT Box_Content.case_number, Transfer.number, Transfer.location, Box.number FROM Box_Content, Transfer, Box WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id and Box_Content.case_number = '".$_POST['casenum']."'");
while ($row = mysql_fetch_array($result2)) {
echo "Case number: ".$casenum." text ";
echo "<br />";
}
} else {
echo "<h4>WARNING!!! Search criteria entered not valid. Please search again.</h4>";
}
What am I doing wrong here?
EDIT:
It works now if only one row is returned, but for two rows, it seems to be trying to print the entire table...
$casenum = $_POST["casenum"];
echo "<br />The case number entered is: $casenum<br />";
if (!empty($_POST["casenum"]))
{
$result2 = mysql_query("SELECT Box_Content.case_number, Transfer.number as transfer_number, Transfer.location as transfer_location, Box.number as box_number FROM Box_Content, Transfer, Box WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id and Box_Content.case_number = '" . $_POST['casenum'] . "'");
while($row = mysql_fetch_array($result2))
{
print_r ($row);
echo "<br />";
echo "<b>Case number: </b>" . $row['case_number'] ."<br />";
echo "<b>Transfer number: </b>" . $row['transfer_number'] ."<br />";
echo "<b>Transfer location: </b>" . $row['transfer_location'] ."<br />";
echo "<b>Box number: </b>" .$row['box_number'] ."<br />";
}
}
else
{
echo "<h4>WARNING!!! Search criteria entered not valid. Please search again.</h4>";
}
var_dump($_POST);

Try:
while ($row = mysql_fetch_array($result2)) {
echo "Case number: ". $row['Box_Content.case_number'] ." text ";
echo "<br />";
}
$row['case_number'] will output the case_number retrieved for each row in your resultset.
However, you should look into doing one of two things:
Start using best practices.
Start using a non-deprecated SQL library (mysqli, PDO).
This query is susceptible to SQL injection:
"SELECT Box_Content.case_number, Transfer.number, Transfer.location, Box.number
FROM Box_Content, Transfer, Box
WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id
and Box_Content.case_number = '".$_POST['casenum']."'"
Use mysql_real_escape_string($_POST['casenum']) to patch this.
Reference: http://php.net/manual/en/function.mysql-real-escape-string.php
The mysql_* functions have long been deprecated due to unprepared statement operations. Look into either mysqli or PDO for your project instead.

What am I doing wrong here?
1) $casenum isn't set in your code... (Please tell me it is nothing and you don't have register superglobals turned on?!) You would probably want $row['case_number']
2) But anyway, that's not really what you are doing wrong... Your biggest mistake is using user input without any kind of validation or sanitization...
Imagine if $_POST["casenum"] was equal to...
' or 1=2 union select user,password,email,salt from users

You seem to be using $casenum from nowhere.
Try:
while($row = mysql_fetch_assoc($result2))
echo "Case number: ".$row['number']." text <br />";
When using the mysql_fetch functions assoc will bring back named indexed data, num will bring back numberic indexed data and array will bring back both, so try to use one or the other.
Then when you do $row = mysql_fetch_assoc($result2) your essentially saying for each row of data returned store it as a (in this case associative) array in $row, so you can then access your data via the standard array commands ($row['foo']).

Related

Method to print MySQL row in PHP using foreach statement?

I am new to PHP and programming, but am attempting to print out the results from each row of one of my MySQL database tables.
Using a set of while loops I achieved this:
while($placeHolder = $query->fetch_assoc()){ // use assoc
echo "<div class='placeHolder'><img src=" . $placeHolder['photo']. " /></div>";
echo "<br />";
}
while($placeHolder2 = $query2->fetch_assoc()){
echo "<div class='placeHolder2'>" . $placeHolder2['name'] . "</div>";
echo "<br />";
}
//etc, etc...
Besides being inefficient, I'm assuming this may also be a security risk.
Is there a better way to do this, possibly using a foreach statement?
Here is my SQL code I forgot to include:
$query = mysqli_query($conx, $sql);
$query2 = mysqli_query($conx, $sql);
$sql = ('SELECT id,name,picture FROM table ORDER BY name DESC LIMIT 50');
I dont think using a foreach statement to print out the results would make it any less safe/unsafe. It really depends on your query. You should be able to print all of them using a foreach doing something like:
$result = $query->fetch_all(MYSQLI_ASSOC);
foreach($result as $row) {
echo $row['photo'];
}
Note** to use fetch_all you would need mysqlnd installed
edit: looking at your query nothing can be injected there. No outside variables being used in the query, so its safe. I would just use the while loop that you originally posted.
edit 2: link to fetch_all documentation: http://php.net/manual/en/mysqli-result.fetch-all.php

Delete and Insert from database

I'm a little bit confused why it does not work.
What i want is that control db if for ex 2012-02-21 exist in DB delete it and insert again but it does not work why
my full code is that but else statement doesnt work :S
$ga->requestAccountData();
$mysql = new mysql();
$mysql->connect();
// $startDate = date("Y-m-d");
$startDate = "2012-02-21";
$dbResult = mysql_query("select * from profiles where profile_Date='".$startDate."'");
$query = mysql_num_rows($dbResult);
if($query > 0)
{
mysql_query("delete from profiles where profile_Date='".$startDate."'");
foreach ($ga->getResults() as $result) {
$ga->requestReportData($result->getProfileId(),array('eventCategory','eventAction'),array('totalEvents'),$sort_metric=null,$filter='eventAction==InitPlayer',$start_date=$startDate,$end_date=$startDate);
foreach($ga->getResults() as $result2)
{
echo $result;
echo $result2->geteventCategory()."<br />";
echo $result2->geteventAction();
echo $result2->gettotalEvents();
"<br />";
"<br />";
"<br />";
$mysql->query("insert into profiles values(" . $result->getProfileId() . ",'" . $result . "','".$result2->geteventCategory()."','".$result2->geteventAction()."','".$result2->gettotalEvents()."','".$startDate."')");
}
}
}
else
{
foreach ($ga->getResults() as $result) {
$ga->requestReportData($result->getProfileId(),array('eventCategory','eventAction'),array('totalEvents'),$sort_metric=null,$filter='eventAction==InitPlayer',$start_date=$startDate,$end_date=$startDate);
foreach($ga->getResults() as $result2)
{
echo $result;
echo $result2->geteventCategory()."<br />";
echo $result2->geteventAction();
echo $result2->gettotalEvents();
"<br />";
"<br />";
"<br />";
$mysql->query("insert into profiles values(" . $result->getProfileId() . ",'" . $result . "','".$result2->geteventCategory()."','".$result2->geteventAction()."','".$result2->gettotalEvents()."','".$startDate."')");
}
}
}
You should use mysql_num_rows to count the results selected and not mysql_affected_rows which applies to queries altering data (insert, update, delete etc.)
$result = mysql_query("select * from profiles where profile_Date='".$startDate."'");
$count = mysql_num_rows($result);
if($count > 0) {
...
}
http://php.net/manual/en/function.mysql-num-rows.php
Why you need to first delete and then insert? you can use update query as well. Also what is the data type of the field profile_Date ? Is it set date or date and time?
You can use MySQL's REPLACE functionality (docs).
It basically works like INSERT, with the exception that if a value with the same key already exists in the database, at first the existing value will be removed and afterwards the new value will be inserted as completely new entry. If there is no existing value, it will behave like INSERT.
Watch out for the differences to UPDATE
The difference to UPDATE is hidden in the details:
since an existing value will actually be removed, all referenced foreign keys constraints will be removed too.
UPDATE will just update the values provided, with INSERT the other columns will get the default value (practical example: a field name timestamp_created with the default value of CURRENT_TIMESTAMP will be unchanged in an UPDATE statement, but will display the current time in a REPLACE statement)

trying to take sql data and then define just one of the rows in a php variable

Hi I have the details of two car drivers getting pulled from a database but then I want to just grab one of the two and echo it out in php. I am able to take both drivers details and echo them both out using a while loop but not target just one of them:
By using the code below I echo out both records. Is there a way to just grab one of them?
while($row = mysql_fetch_array($result))
{
echo "A driver:<br />";
echo "Name:". $row['FirstName'] . " " . $row['LastName']."<br />";
echo "Latitude:". $row['CoordLat']."<br />";
echo "Longitude:". $row['CoordLong'];
$driverlat = $row['CoordLat'];
$driverlong = $row['CoordLong'];
}//end of while loop
Just remove the while loop ?
$row = mysql_fetch_array($result))
echo "A driver:<br />";
echo "Name:". $row['FirstName'] . " " . $row['LastName']."<br />";
echo "Latitude:". $row['CoordLat']."<br />";
echo "Longitude:". $row['CoordLong'];
$driverlat = $row['CoordLat'];
$driverlong = $row['CoordLong'];
You don't need a while loop at all.
Just do $row = mysql_fetch_array($result); on it's own separate line.
This will display the first row result.
You can just put a break; at the end of the while loop. Then only the first row is processed.
Better way would be to use no loop: Just assign the $row and do the render stuff.

How to give a unique url/id to a question posted by the user?

There's a form called discussion.php, in which a user will fill out his/her question/discussion and post it to savedisc.php. Some of the savedisc.php looks like this:
$message = $_POST['message'];
$title = $_POST['title'];
$represents = $_POST['represents'];
//connect to database
//save the content of discussion/question into the database for future use
$sql="INSERT INTO Discussion (Message, Title, Type)
VALUES
('$message','$title','$represents')";
//Display user's question/discussion again
echo $message . "<br />";
echo $title . "<br />";
echo $represents . "<br />";
It is not shown above, but I am saving the id field manually, i.e. via phpmyadmin as a auto increment and primary key of course. Therefore, all of the values in the table Discussion will have their own unique id. Once the question/discussion is saved, I want to be able to display $title of each question on wb.php as a link, which as of now looks like this(some code from wb.php):
$result = mysql_query("SELECT * FROM Discussion ORDER BY id DESC");
//When user clicks the question/discussion Title, he/she will be directed to wbcomm.php
while($row = mysql_fetch_array($result))
{
echo "<a href='wbcomm.php' >{$row['Title']}</a><br />";
}
Until here, everything is working smooth. However, from here on, what I'm trying to do is, when the user clicks the question/discussion title via above code, I want him/her to be directed to wbcomm.php?id=1, where id=1 represents the unique id of the question/discussion. Some of the code from wbcomm.php is below:
if (isset($_GET['id']))
{
//connect to db
$wbid = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM Discussion WHERE id = '$wbid' LIMIT 1";
$res = mysql_query($sql);
if (mysql_num_rows() > 0) {
$discussion = mysql_fetch_object($res);
//display member's question here:
echo $discussion['id'] . "<br />";
echo $discussion['Title'] . "<br />";
echo $discussion['Type'] . "<br />";
echo $discussion['Message'] . "<br />";
}
else {
// discussion does not exist with ID
}
}
However, for some reason, the result is blank. I.e. the question/discussion doesn't even show up. What am I doing wrong? Is my procedure even correct?
Thank you.
In your wb.php, you create a link to wbcomm.php but you are not passing the ID of the discussion, so your $wbid will be empty. You need to pass the ID along with the link, like this:
while($row = mysql_fetch_array($result))
{
echo "<a href='wbcomm.php?id={$row['id']}' >{$row['Title']}</a><br />";
}
Your ID column is an autoincrement int type so you do not need to put it in quotes or escape it. You should definitely test it to see if it's numeric, though.
Use this SQL mysql_num_rows($res) > 0

How to fix this simple MySQL display order issue

I'm very new to MySQL so I need some help please,
I have a table called "posts", this table has the following columns:
id - this is auto increment and primary key
title
content
I have a PHP page where I want to display all the posts from the database table. I want the title to show first and then the post content followed by the title of the next post and it's post content and so on... However if I do this:
$select = mysql_query("SELECT * FROM posts ORDER BY id DESC");
while ($result = mysql_fetch_array($select))
{
echo $result['title'] . "<br />";
echo $result['content'];
}
Of course I get a list of all my post titles followed by all my post contents. In other words it's like this:
DogsCats
Are also known as canines.Are also known as felines.
Instead of:
Dogs
Are also known as canines
Cats
Are also known as felines
What would I need to do to fix this?
Many thanks.
What about
while ($result = mysql_fetch_array($select))
{
echo $result['title'] . "<br />";
echo $result['content'] . "<br /><br />";
}
You're missing a line break after your content, so first occurrence would be fine, but it'll merge first content with second title.
Try the following for your loop:
while ($result = mysql_fetch_array($select))
{
echo $result['title'] . "<br />" . $result['content'] . "<br />";
}
Alternatively:
while ($result = mysql_fetch_array($select))
{
printf("%s <br /> %s <br />", $result['title'], $result['content']);
}
You should tell PHP what kind of array you want (MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH).
Since you are using column names as array subscripts, you should use MYSQL_ASSOC or MYSQL_BOTH:
while ($result = mysql_fetch_array($select, MYSQL_ASSOC))
...

Categories