how to add a if confition to a mysql query? - php

i am trying to add an if statement to a mysql query so that it checks the user exists from a table called ptb_users in the user_id column before the query runs.
users can write on other users walls and before a user can write on a users wall / before the query inserts into ptb_wallposts, i want it to check that the from_user_id = the ptb_users.user_id.
i am trying to do this but i get syntax errors all over my page can someone please can someone show me how i would need to structure this:
<?php
// check if the review form has been sent
if(isset($_POST['review_content']))
{
$content = $_POST['review_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['review_content']!='')
{
if exists (select user_id from ptb_users where user_id = #id)
begin
{
$sql = "INSERT INTO ptb_wallposts (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
mysql_query($sql, $connection);
$_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Wall Post Added</strong> - Your comment was posted to {$profile[2]}'s wall.</div><div class=\"infobox-close4\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} }
}
end
else
begin
echo "error user doesnt exist"
end
?>

Here's an example of if statement (from MySQL Reference)
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
Let me explain a little more better, i'll compare between PHP and SQL if statements
PHP:
IF(variable > 0){
anything..
}
SQL:
IF variable > 0 THEN anything..
Read more:MySQL Reference - IF STATEMENT

Related

mysql insert into creates 2 records in table row

Ok .. I'm stuck. I tried several codes from topics here, but still not working for me so I need a little help please.
I want to log if a user is logged in for the first time and want to update that same record if the user returns. The update part works, but when my function is executed the first time, it insert a total blank record and a record with all the data provided by variables. The last_login column is NULL for the first vist and is nicely updated with the last login.
But what I can't figure out is why the first login creates these extra records.
Here is the function code I created:
function log_users($userId, $username, $achternaam, $district, $gemeente, $ipaddress)
{
global $connection;
$sql = mysqli_query($connection, "SELECT * FROM logfile_sap WHERE user_id = '{$userId}'");
if(mysqli_num_rows($sql) > 0)
{
$sql = "UPDATE logfile_sap SET last_login = NOW() WHERE user_id = '{$userId}'";
$query = mysqli_query($connection, $sql);
}
else
{
$sql = "INSERT INTO logfile_sap
(user_id, username, achternaam, district, gemeente, ipaddress, first_login)
VALUES
('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW())";
$query = mysqli_query($connection, $sql);
}
}
So as you can see I am checking if the user already exists in the logfile_sap table and if it does NOT exist I want to insert the user (which works but with an extra row) and if the user already exists the record is updated.
This is the code I use on top of the page that needs to check and adds the data in the table:
<?php log_users($userId, $username, $achternaam, $district, $gemeente, $ipaddress); ?>
I hope some has a brighter idea than me ;-)
++++++++++++++++++++++++++++++++++++++++++++
Problem SOLVED. I had an epiphany !!!
I called my function OUTSIDE my if(isset($_SESSION['id'])) statement.
After I've put it INSIDE the if(isset($_SESSION['id'])) statement, there was only one record inserted into the table !!
Problem SOLVED. I had an epiphany !!!
I called my function OUTSIDE my if(isset($_SESSION['id'])) statement.
After I've put it INSIDE the if(isset($_SESSION['id'])) statement, there was only one record inserted into the table !!

Executing this query if user has a row in DB, else not

I have a table called user_bio, this table has one row, which was inserted manually:
id: 1
age: 30
studying: Business
language: English
relationship_status: Single
username: conor
about_me: This is conor's bio.
I have a page called account_settings_bio.php, from where the logged in user ($username) can edit their details. At the moment, when I log in as conor, I can UPDATE my data, but say for example I log in as Alice, Alice has no row in the database, therefore, I would have to INSERT data for her, but it doesn't seem to insert a new row for her.
Here is my approach:
if ($update_bio){
/*************************/
// need to check if the username has data already in the db, if so, then we update the data, otherwise we insert data.
$get_bio = mysqli_query($connect, "SELECT * FROM user_bio WHERE username ='$username'");
$row_returned = mysqli_num_rows($get_bio);
if ($row_returned == 1){
$update_details_query = mysqli_query ($connect, "UPDATE user_bio SET studying ='$new_studying', language ='$new_lang',
relationship_status = '$new_rel', about_me = '$about_me' WHERE username ='$username'");
} if ($row_returned == 0) {
$insert_query = mysqli_query ($connect, "INSERT INTO user_bio VALUES ('', '$age', '$new_lang','$new_rel', '$username', '$about_me'");
}
echo " <div class='details_updated'>
<p> Details updated successfully! </p>
</div>";
}
The UPDATE query works fine, when logged in as conor, data does change in the db, its just the INSERT which is not working.
The order of the inserted columns is not the same as in the database and there are missing some (studying).
To be sure, you could rewrite your insert SQL to be more explicit:
INSERT INTO user_bio (id, age, studying, language, relationship_status, username, about_me) VALUES (NULL, '$age', '$new_studying', '$new_lang','$new_rel', '$username', '$about_me'"
Note: why not use if($row_returned==0){ /* INSERT */ } else { /* UPDATE */ } instead of a double if?

How to update multiple fields in Database

I have a databse photos in which the record of members are stored, it has name, au_id , position , contact & email columns. There is secured panel where admin can change the details of the body members of the group. Complete form is shown again here with the values stored in database so if admin want to change any value he/she can do here and submit that form to update record. On successfull submission
$name=$_POST['name'];
$au_id=$_POST['au_id'];
$position=$_POST['position'];
$contact=$_POST['contact'];
$email=$_POST['email'];
I am having trouble to update records of particular member. I have primary key id in my database. I am using:
$save="UPDATE photos SET name = '$name', au_id = '$au_id', position = '$position', cell = '$contact', email = '$email' WHERE id = '6' ";
$result=mysql_query($save);
and putted a check so that i can know that if query is successfully run or not,
if (mysql_num_rows($result))
{
echo 'successfully updated';
}
else
{
echo 'not updated';
}
it is giving successfully updated message but when i again go to check the records nothing is changed. how can i figure out this problem
$save="UPDATE photos SET name = '".$name."', au_id = '".$au_id."', position = '".$position."', cell = '".$contact."', email = '".$email."' WHERE id = '6' ";
$result=mysql_query($save);
$save="UPDATE photos SET name = '$name', au_id = '$au_id', position = '$position', cell = '$contact', email = '$email' WHERE id = '6' ";
if ($result=mysql_query($save))
{
echo 'successfully updated';
}
else
{
echo 'not updated';
}
mysql_num_rows should not be used for the SQL querys which does not return result set, like UPDATE, DELETE and so on.
mysql_query it self seems to work in some situations if mysql connection is properly done by mysql_connect and db is properly selected using mysql_select_db. So you should check whether the SELECT query works there.
However, if one of field contains "'", for example, your SQL query is collapsed. This is not just a problem which leads to error, but a vulnerability which allows "SQL injection". You should use placeholder. If placeholder can't be used for some reason, you must use mysql_real_escape_string to escape your fields.
As you are mention in your question columns are :-
name, au_id , position , contact & email
two things I have catch in your code:-
1) You are mention contact column and your updating with cell.
2) You have not declare $contact variable.
Please run query with correct column name and if id is not string then no need to use id = '6' you can use id = 6
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.check this link
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
So you get true or false on executing the query and obviously mysql_num_rows(true) makes no sense.
try this:
use mysql_affected_rows()
$save="UPDATE photos SET name = '$name', au_id = '$au_id', position = '$position', cell = '$contact', email = '$email' WHERE id = '6' ";
$result=mysql_query($save);
$cnt=mysql_affected_rows();
if($cnt>0)
{
echo 'successfully updated';
}
else
{
echo 'not updated';
}
mysql_ is deprecated function

INSERT INTO table1 values FROM table2 WHERE

I've looked around nothing seems to be working for me. I have a button when pushed it INSERTS data into 1 table-1, then it gets values from table-3 to put in table-2 where in they the ID is the same.
if ($movieTime != "") {
$query = "SELECT SchedID FROM tblCinemaSched WHERE TheaterID='$tid' AND CinemaID='$cid' AND MovieDate='$date' AND MovieTime='$movieTime'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$numRows=$conn->numRows($result);
if ($numRows<=0) {
$query = "INSERT INTO tblCinemaSched SET TheaterID='$tid', CinemaID='$cid', MovieDate='$date', MovieTime='$movieTime', MovieID='$movieId', PriceAmt='$priceId', CrtBy='$username', CrtDate=NOW()";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
//get seat defaults from tblCSeats
$query = "INSERT INTO tblSSeats SELECT TheaterID, CinemaID, '$date', '$movieTime', SeatID, RowNo, ColumnNo, Handicap, Status, LeftSeat, RightSeat, NULL, NULL,NULL,NULL,NULL,NULL,NULL,'$username',NOW() FROM tblCSeats WHERE TheaterID='$tid' AND CinemaID='$cid'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$errorStr = "Succesfully added schedule.";
}
else {
$errorStr = "There's already an existing schedule for the specified time.";
}
You see tableCSeats has more than 1 row that has the same ID meaning I want to insert multiple data from tableCSeats to tableSSeats. tableSSeats is a has no data in it yet.
At a blind guess, it would seem that you are looking for INSERT ... SELECT statement.
check the return values of your queries. You always get "Succesfully added schedule." because you don't check if the queries were succesful. Ex:
if(!$result=$conn->executeUpdate($query)) {
die('error');
}
or something like that.

PHP How to edit database entry I just created? (basic)

In my site, I have a page to create an site page (addpage.php) and then send the user to a listing of all pages (pages.php), from which they can click on the page they'd like to edit (editpage.php).
I do this because my editpage.php uses the page_id variable to select the page's info from the database and I don't know how to select that variable without first going to pages.php to list all those variables.
I'd like to be able to complete addpage.php and then GO DIRECTLY to editpage.php - but how do I select the page_id that will only just be created on the insert into the database?
My code on addpage.php is basically
$q = "INSERT INTO pages (page_name, page_content) VALUES ('$name', '$content' )";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// send to pages.php
} else { // If it did not run OK.
echo '<p>The page has NOT been added</p>';
}
$q = "INSERT INTO pages (page_name, page_content) VALUES ('$name', '$content' )";
$r = mysqli_query ($dbc, $q);
$id=mysql_insert_id();
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// send to pages.php
} else { // If it did not run OK.
echo '<p>The page has NOT been added</p>';
}
You can check php manual.
You have to do a query to your database, asking what've been the last inserted id. You can do this running this query:
SELECT LAST_INSERT_ID() as lastId
Then you get the value as you do with any regular query (because this is a regular query actually).
In php there's a function called mysql-insert-id which is more elgant.
Good luck!
If you're using mysql, you can get the ID of the last insert by running the following query SELECT LAST_INSERT_ID(). This will get you the ID.

Categories