Delete and Insert from database - php

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)

Related

List all table contents from generated list of table column names

I have got one piece of code which gives me a list of all the column names for a specific table. Can i use this list as my $row['VARIABLE'] instead of specifying every row?
The current output of the table names can be seen here this is the second paragraph of text, the first ones are my table names (USERS, ADMIN_LOGIN)
I am working on making a small script which will list all the table contents of a table but it is likely the table will change often so i want a script which can auto generate the table of contents without me having to manually re-enter it all as i have done in the second piece of code below?
Thanks guys
<?php
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
echo $table['name'] . '<br />';
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
echo "ID = ". $row['ID'] . "\n";
echo "USERNAME = ". $row['USERNAME'] ."\n";
echo "AGE = ". $row['AGE'] ."\n";
echo "LOCATION = ".$row['LOCATION'] ."\n\n";
echo "ANYTHING_ELSE = ". $row['ANYTHING_ELSE'] . "\n";
echo "EMAIL = ". $row['EMAIL'] ."\n";
echo "PROFILE_APPROVED = ". $row['PROFILE_APPROVED'] ."\n";
echo "NUMBER_OF_BATTLES = ".$row['NUMBER_OF_BATTLES'] ."\n\n";
echo "TOTAL_WINS = ".$row['TOTAL_WINS'] ."\n\n";
}
?>
Yes, you can use variables for the index values of an array. For example,
$row = array('col_name' => 'column value');
$index = 'col_name';
echo $row[$index]; // Equivalent to $row['col_name']. Prints "column value"
You should be able to accomplish what you want pretty easily using the above logic. Basically just store the column names from the first query into an array, then loop through that array to get the column names each time you print a row.
Give this a try:
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
foreach ($columns as $col)
echo $col . " = " . $row[$col] . "\n";
}
I use the following in order to get a list of columns names in the order they are defined in the table. I use it to populate an insert/select when preserving data.
sel columnname
from dbc.columns
where databasename='databasename'
and tablename='tablename'
order by columnid;

simple MySQL query via 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']).

no results shown when I enter the if statement

This is the part of the PHP code I am having the issue:
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_fetch_array($result) == False) echo "Sorry, no clients found";
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo "<br />";
echo $list;
}
Even if I insert an existing idcard value I get no output when there is the if statement, an incorrect idcard displays "Sorry, no clients found" fine. However if I remove the if statement if I enter an existing idcard the data displays ok.
Can you let me know what is wrong with the code please ?
Thanks
Use mysqli_num_rows to count the results:
if(mysqli_num_rows($result) == 0) echo "Sorry, no clients found";
mysqli_fetch_array() fetches an item from the database.
This means your if() code fetches a first item from the database.
Then, when you call mysqli_fetch_array() again from the while() condition, the first item has already been fetched, and you are trying to fetch the second one ; which does not exist.
You must ensure that you use the result from mysqli_fetch_array() and not call it one time just for nothing ; or, as an alternative, you could use the mysqli_num_rows() function (quoting) :
Returns the number of rows in the result set.
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
}else{
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo $list . "<br />";
}
}
Try this.
EDITED: Added closing bracket.
Use mysqli_num_rows() to test if there is anything returned.
Imagine you put some money in your pocket.
Eventually an idea came to your mind to see if you are still have the money.
You are taking it out and count them. All right.
Still holding them in hand you decided to take them from pocket. Oops! The pocket is empty!
That's your problem.
To see if you got any rows from the database you can use mysqli_num_rows(). It will return the number of bills, without fetching them from the pocket.
The problem is, that you try to use mysqli_fetch_array to queck for the number of results. mysqli_fetch_array will fetch the first result, compare it to false and then discard it. The next mysqli_fetch_array will then fetch the second result, which is not existing.
If you want to check if any clients where found, you can use mysqli_num_rows like this:
$idcard = mysqli_escape_string($dbc, $idcard); // See below: Prevents SQL injection
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query) or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
} else {
while($row = mysqli_fetch_array($result)) {
// Do whatever you want
}
}
If $idcard is a user supplied value, please look out for SQL injection attacks.

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