I have following code. With a single select query and an update query.It is working fine when i remove the update query. When i run following complete code then nothing happens.
Please help me I want to update table with every cycle of select query. Is there any way to execute following code.
$query = "SELECT * FROM ab_rec WHERE username='$userid'" or die(mysql_error());
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
$t_name=$row['testname'];
$first_url=$row['first_url'];
$thanks_url=$row['thanks_url'];
$start_date=$row['start_date'];
$parse_first_url = parse_url($first_url); //parsing URL of first page for removing main domain name from it.
$parse_thanks_url = parse_url($thanks_url);
$final_first_url = $parse_first_url['path'] ; //Finally parsed URLs are stored into new variables
$final_thanks_url = $parse_thanks_url['path'] ;
$row['unique_visits'] = calculate_visitors($final_first_url, $start_date);
$row['conversions']= calculate_visitors($final_thanks_url, $start_date);
$row['conversion_percent'] = ($conversions/$unique_visits_first)*100;
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'], conversions=$row['conversions'] , conversion_percent=$row['conversion_percent'], WHERE testname=$row['testname'] " or die(mysql_error());
$result2=mysql_query($query1, $connection);
echo "<tr><td>" . $checkbox . "</td><td>" ."<a href='my_test.php?test_name=$t_name'>".$row['testname'] . "</a></td><td>" . $row['date_of_creation'] . "</td><td>" . $row['unique_visits'] . "</td><td>" . $row['conversions'] . "</td><td>" . $row['conversion_percent'] ."%". "</td></tr>"; //$row['index'] the index here is a field name
}
This:
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'],
conversions=$row['conversions'] , conversion_percent=$row['conversion_percent'],
WHERE testname=$row['testname'] " or die(mysql_error());
$result2=mysql_query($query1, $connection);
Should be:
$query1="UPDATE `ab`.`ab_rec` SET unique_visits=$row['unique_visits'],
conversions=$row['conversions'] , conversion_percent=$row['conversion_percent']
WHERE testname='{$row['testname']}'";
echo $query1; //POST THIS RESULT
$result2=mysql_query($query1, $connection) or die(mysql_error());
Related
$sql = mysqli_query($conn, "SELECT * FROM stock WHERE Date = '$date'");
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
$d="D-";
// output data of each row
echo "<table><tr><th>ID</th><th>Date</th><th>Product Code</th><th>Description</th><th>Delivery Order</th><th>Cartons</th><th>Items</th><th>Quantity</th><th>Sent_To</th></tr>";
while($row = $result->fetch_assoc())
{
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["Date"]. "</td><td>" . $row["Product_Code"]. "</td><td>" . $row["Description"]. "</td><td>".$d. $row["DEO"]. "</td><td>" . $row["Cartons"]. "</td><td>" . $row["Items"]. "</td><td>" . $row["Quantity"]. "</td><td>" . $row["Sent_To"]. "</td></tr>";
}
echo "</table>";
Hello Guys When i echo $date it prints the date correctly but when i run this query i get an error
Warning: mysqli::query() expects parameter 1 to be string, object
given in C:\xampp\htdocs\rmt\displaydate.php on line 9
Notice: Trying to get property of non-object in
C:\xampp\htdocs\rmt\displaydate.php on line 11
Please help me to fix this error. Thanks in advance.
You're calling mysqli_query followed by $conn->query on the result from the first query. You only need to call one of them, for example;
$sql = "SELECT * FROM stock WHERE Date = '$date'";
$result = $conn->query($sql);
I've now been trying for hour and can't figure the problem out. I've made a php file that fetch all items in a table and retrieves that as JSON. But for some reason after I inserted the second mysql-query, it stopped fetching the first item. My code is following:
...
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
$row2 = $result2->fetch_assoc();
while($row = $result2->fetch_assoc()) {
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,
strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
Any help is greatly appreciated.
EDIT: Thanks for all those super fast responses.
First you're fetching a row:
$row2 = $result2->fetch_assoc();
Then you start looping at the next row:
while($row = $result2->fetch_assoc()) {
If you want to loop over all of the rows, don't skip the first one. Just loop over all of the rows:
$result2 = // your very SQL-injectable query
while($row2 = $result2->fetch_assoc()) {
$result3 = // your other very SQL-injectable query
$row3 = $result3->fetch_assoc();
// etc.
}
Note that errors like this would be a lot more obvious if you used meaningful variable names. "row2", "result3", etc. are pretty confusing when you have overlapping levels of abstraction.
Important: Your code is wide open to SQL injection attacks. You're basically allowing users to execute any code they want on your database. Please look into using prepared statements and treating user input as values rather than as executable code. This is a good place to start reading, as is this.
No Need of $row2 = $result2->fetch_assoc();
<?
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
while($row = $result2->fetch_assoc())
{
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
?>
Or,
<?
...
case "LoadEntryList":
$Category=$_POST["Category"];
$Offset=$_POST["Offset"];
$Quantity=$_POST["Quantity"];
$result3 = performquery("SELECT Entries.*, Users.Username FROM Entries, Users WHERE Entries.Category=$Category AND Entries.UserID=Users.ID LIMIT $Offset, $Quantity");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
?>
I have a addition to David answer(can't comment on it yet)
This line of code:
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
will always return with the same result. If you were to change $row2[... into $row[... the code would take the rows that get updated by the while loop.
I am not content with the accepted result. The snippet can be fixed / replaced, and also a bad code must be replaced. Also not to mention is that I don't know if anyone spotted a really big mistake in the output. Here is the fix and I'll explain why.
$JSON = array();
$result2 = performquery( '
SELECT
e.*, u.Username
FROM Entries AS e
LEFT JOIN Users AS u ON u.ID = e.UserID
WHERE
e.Category = ' . $_POST['Category'] . '
LIMIT ' . $_POST['Offset'] . ', ' . $_POST['Quantity'] . '
' );
while( $row2 = $result2->fetch_assoc() ){
$JSON[] = $row2;
}
echo json_encode( $JSON );
Obviously the main issue is the query, so I fixed it with a LEFT JOIN, now the second part is the output. First it's the way you include the username, and the second what if you had multiple results? Than your output will be:
{"ID":1,"Username":"John"}{"ID":2,"Username":"Doe"}
How do you parse it? So the $JSON part comes in place. You add it to an array and will encode that array. Now the result is:
{["ID":1,"Username":"John"],["ID":2,"Username":"Doe"]}
LE: I left out the sql inject part which as stated by the OP, will be done afterwards? I'm not sure why not do it at the point of writing it, because you may forget later on that you need to sanitize it.
Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}
what am trying to do here is get data from mysql generated checkboxes. The check boxes data are in array . So for all the check boxes selected I want to use each as a parameter in a query to get more info from another databastablee.
Sample Code Below
if (isset($_POST['submitCourseCode'])) {
//GET ARRAY FROM DATABASE GENERATED CHECKBOXES
$aElective = $_POST['electiveModules'];
foreach($aElective as $snode) {
echo "$snode <br />";
}
//PASSING EACH DATA FROM ARRAY INTO QUERY
$Query = "SELECT ID,title,credits
FROM module
WHERE ID IN('" . implode("', '", $aElective) ."')";
$Result = mysql_query($Query)
or die ("Query failed: " . mysql_error() . " Actual query: " . $Query);
while ($Row = mysql_fetch_array($Result)) {
$id = htmlentities($Row['ID']);
$title = htmlentities($Row['title']);
$credits = $Row['credits'];
echo "<ul>" . $id . " " . $title . " " . $credits . "</ul>";
}
}
var_dump($Query);
var_dump($Result);
var_dump($Row);
Screenshot of my result
Am guessing something is happening with my query probably because of the implode function but everything seems fine in my query.Any suggestions on what am doing wrong?
You need to trim array elements using array_map('trim', $aElective) as:
$Query = "SELECT ID,title,credits
FROM module
WHERE ID IN('" . implode("','", array_map('trim', $aElective)) ."')";
There is a problem with white spaces before your IDs in IN clause.
Try to add a str_replace() call
$Query = "SELECT ID,title,credits
FROM module
WHERE ID IN('" . str_replace(" ", "", implode("', '", $aElective)) ."')";
Total newbie trying to learn... thanks for all the help so far!
UPDATE - updated code below - Thanks Phill
I'm now trying to get the relevant horse information from a table horses which I can join to race_form with the horse_name field. I want to then display the information for each horse in the race below the while($racecard) info. Does this make it a bit clearer?
I thought I could just do another query and then a while loop with mysql_fetch_array below the one I have already and that would display it and then move onto the next race, but that apparently doesn't work...?!
I'm wondering if you can run 2 while loops after each other inside a while loop? I am working on a horse racing formguide - I can display each race list, but underneath I want to display individual horse details on each horse in the race. Anyway if you look at this page you can see what I'm trying to do:
http://tasmanianracing.com/superform/formguide.php?meetingID=21042011LAUN&Submit=View+Form
Problem is, any time I put a second while loop after the race list, it won't show up. I'm trying to run a query to get the horse details from my horse table and then run a while for each horse in the race, but nothing shows up.
I hope this is clear enough ... my snippet of code is below - please let me know if I've missed out something important:
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $row['race_number'] . " at " . $row['start_time'] . " " . $row['class'] . " over " . $row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $row['raceID'] . "')");
while($row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $row['number'] . "</td><td>" . $row['past10'] . "</td><td>" . $row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
echo "</table>";
You'll probably need to change the names of some of the $row variables, they may interfere with each other.
For example:
while($row_races = mysql_fetch_array($totalraces)){
while($row_details = mysql_fetch_array($racedetails)){
while($row_card = mysql_fetch_array($racecard)){
I think you can get rid of one of your queries:
The first query gets the number of races by selecting a COUNT, This returns one record with the count value.
// This returns one record with the count
$total_races = "SELECT COUNT(race_number) AS totalraces
FROM race_info WHERE meetingID = ('".$safemeetingID."') ";
Next you iterate over the the same records as the rows returned for the race details are the same as the count.
// This looks to return the record(s) with the race details
$race_details = "SELECT * FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')";
I think you can just use this to get the desired results: (I agree to rename the $row variable(s) to something descriptive for each while loop)
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
NOT TESTED/PSEUDO CODE
"SELECT *
FROM horses AS h,
INNER JOIN race_info AS ri ON race_form.raceID = race_info.raceID
WHERE horse_name IN (
SELECT horse_name
FROM race_form AS srf
WHERE h.horse_name = srf.horse_name
)
AND race_form.raceID = ('" . $details_row['raceID'] . "')"
The idea is to join the two queries into one, I know this is not the correct syntax but it might give you an idea on how to go about it.
Or you can do another query while loop for the horse names
$racedetails = mysql_query("SELECT *
FROM race_info
WHERE meetingID = ('" . $safemeetingID . "')");
while($details_row = mysql_fetch_array($racedetails))
{
echo "<tr><td>Race " . $details_row['race_number'] . " at " . $details_row['start_time'] . " " . $details_row['class'] . " over " . $details_row['distance'] . "m</td></tr>";
$racecard = mysql_query("SELECT *
FROM race_form
INNER JOIN race_info ON race_form.raceID = race_info.raceID
WHERE race_form.raceID = ('" . $details_row['raceID'] . "')");
while($rc_row = mysql_fetch_array($racecard))
{
echo "<tr><td>" . $rc_row['number'] . "</td><td>" . $rc_row['past10'] . "</td><td>" . $rc_row['horse_name'] . "</td></tr>";
$horses = mysql_query("SELECT *
FROM horses
WHERE horse_name = ('" . $rc_row['horse_name'] . "')");
while($horse_row = mysql_fetch_array($horses))
{
// echo horse details here
}
}
echo "</table><br>";
echo "Testing<br>Testing<br>I wish I could put in some horse form here...<br>";
echo "<table width='990' border='1' cellspacing='2' cellpadding='2'>";
}
I theory you could and in practice you can, but a while in a while in a for in a while seems a little bit over the top...
I'm sure we can help you make it more efficient if you explain what it is you're trying to do.