I have some problem with my if else statement, but I cant figure out what, since it should work :)
What im trying to do is that IF the video_title already exist in my row then do nothing,
but if the video_title does not exist, insert values to the table.
I have the value marvel.mp4 in my video_title column,
But it still keeps on inserting marvel.mp4 as value on new rows...
Any ideas why its not working?
$query = $dbh->query("SELECT video_title FROM video");
$q = $query->fetch(PDO::FETCH_OBJ);
$video_title = "marvel.mp4";
if($video_title ==$q){
// Do Nothing
}else{
$sql = "INSERT INTO video (video_title, video_cat, video_date) VALUES (:video_title, :video_cat, NOW())";
$query = $dbh->prepare($sql);
$query->execute(array(
':video_title' => $video_title,
':video_cat' => $video_cat
));
}
It should be:
if ($video_title == $q->video_title)
When you use PDO::FETCH_OBJ, each column is a property of the object.
You also need to be more specific in the query, otherwise you're just testing whether the video is the first one returned by the query.
$video_title = "marvel.mp4";
$stmt - $dbh->prepare("SELECT video_title FROM video WHERE video_title = :title");
$stmt->execute(array(':title' => $video_title));
$q = $stmt->fetch(PDO::FETCH_OBJ);
This code will solve your problem. I have just tested and run it and is working.
Please rate me if you find this help awesome ....Sectona
<?php
$db = new PDO (
'mysql:host=localhost;dbname=sectona_db;charset=utf8',
'root', // username
'tt56u' // password
);
?>
<?php
require("pdo.php");
$video_t=strip_tags($_POST["video_t"]);
//check if the video title already exist in the database
$result = $db->prepare('SELECT * FROM video where video_title = :video_title');
$result->execute(array(
':video_title' => $video_t
));
$nosofrows = $result->rowCount();
if ($nosofrows == 1)
//if ($nosofrows ==0)
{
echo '<br><b><font color=red><b></b>Video Title Already exist. Do not insert</font></b><br>';
exit();
}else{
// insert data
$statement = $db->prepare('INSERT INTO video(video_title,video_name)
values
(video_title,video_name)')
$statement->execute(array(
':video_title' => $video_t,
':video_name' => 'Commando'
));
}
?>
Related
The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.
I'm making a simple webshop for my university project that uses two tables from database (users and items).
I try to insert into the database some information about the specific item. The last column is the id of the logged user. I make query that receiving from 'users' table the id of the actually logged user.
When I use this variable ($lastlogin) printing via echo it shows a correct value.
Unfortunately when I try to insert the id to the table 'items' with insert query, there goes 0 instead of the correct value (eg. 5).
Does anyone know how to fix my problem? I will be grateful.
$idlogin = "SELECT id FROM users WHERE login=:login";
$query = $db->prepare($idlogin);
$query->bindParam(":login", $_SESSION['login']);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$lastlogin = $row["id"];
$sql = "INSERT INTO `items` VALUES (NULL, :name, :description, :cust_id)";
$params = [ ":name" => trim($_POST["name"]),
":description" => trim($_POST["description"]),
":cust_id" => '$lastlogin'];
$query = $db->prepare($sql);
$query->execute($params);
You don't have to put $lastlogin between quotes in your params. If you do, mysql will see this as a string with the value "$lastlogin". Mysql won't be able to parse this to an integer and add the value 0 instead.
$params = [
":name" => trim($_POST["name"]),
":description" => trim($_POST["description"]),
":cust_id" => $lastlogin
];
Ok, thanks for everyone who tried to help me
I found a clue in Michael Berkowski response at this thread
$lastlogin was initialized only the first time, so I put it into $_SESSION['lastlogin'] and call it in sql query.
$idlogin = "SELECT id FROM users WHERE login=:login";
$query = $db->prepare($idlogin);
$query->bindParam(":login", $_SESSION['login']);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$lastlogin = (int)$row["id"];
$_SESSION['lastlogin'] = $lastlogin;
$sql = "INSERT INTO items VALUES (NULL, :name, :description, :cust_id)";
$params = [
":name" => trim($_POST["name"]),
":description" => trim($_POST["description"]),
":cust_id" => $_SESSION['lastlogin']
];
$query = $db->prepare($sql);
$query->execute($params);
Now everything works great. Thanks again for your time.
I am really beginner on PHP and Android and I can't find the problem.
Here is the by return book PHP code.
Firstly it takes two variables Id and id. It selects id from Books database if the id matches it store the Books database variables.
If takenby === Id it should assign true to $success, otherwise it should assign false to $success but every time $success is null.
I don't understand why it is always null.
Thank for your answering...
<?php
$con = mysqli_connect("localHost","name","password","database");
$id = $_POST["id"];
$Id = $_POST["Id"];
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($con, 'utf8');
$statement2 = mysqli_prepare($con, "SELECT * FROM Books WHERE id = ?");
mysqli_stmt_bind_param($statement2,"s" , $id);
mysqli_stmt_execute($statement2);
mysqli_stmt_store_result($statement2);
mysqli_stmt_bind_result($statement2, $name, $author, $ıd, $date, $takenby);
$response = array();
$response["success"] = false;
if($takenby===$Id)
{
$statement = mysqli_prepare($con,"UPDATE Books SET takenby = '' , date = '' WHERE id = ?");
mysqli_stmt_bind_param($statement,"s" , $id);
$success = mysqli_stmt_execute($statement);
}
$response = array();
$response["success"]=$success;
$response["id"] = $id;
//json data formatı
echo json_encode($response);
mysqli_close($con);
?>
Here is the console output,
Value null at success of type org.json.JSONObject$1 cannot be converted to boolean.
The problem is in that script is missing the fetch part. After I realized that fetch is missing, and I fetch statement.
Here is some example from PHP documentation about fetch
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?> [1]
If someone encounters some kind of problem, ı hope that it would help.
[1] http://php.net/manual/en/pdostatement.fetchall.php
please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}
I'm pretty much a novice when it comes to coding, so sorry for lack of knowledge here.
I'm trying to retrive a forigne key attribute from one database table (the user's ID number) so I can then make that id a variable which will be used to save the details into another database table.
From that I can view all of the saved records linked with that user's id when they are logged in.
My problem is with getting the user ID and making it a variable to save into the database, I just can't seem to make it work. The rest of the code works if I remove the user ID but I need that to save into the table.
Here's my code:
require_once( "dbconnect.php" );
try
{
$db = getConnection();
function get_id($db)
{
$username= $_SESSION['username'];
$result = $db->query(
"SELECT userID FROM users where username='$username'");
return $result;
}
$uID = get_id($db);
$userID= $uID->setFetchMode(PDO::FETCH_NUM);
$title = $Result->title;
$desp = $Result->description;
$sql = "INSERT INTO saved (userID, title, desp
VALUES ('$userID', '$title', '$desp')";
The proper way
function get_subid($db,$username)
{
$stm = $db->prepare("SELECT userID FROM users where username=?");
$stm->execute(array($username));
return $stm->fetchColumn();
}
$userID = get_subid($db,$_SESSION['username']);
try removing the quotes around userid variable in your query :
$sql = "INSERT INTO saved (userID, title, desp) VALUES ($userID, '$title', '$desp')";
Try the following:
require_once( "dbconnect.php" );
try {
/** * ** connect using the getConnection function written in myfunctions.php ** */ $db = getConnection();
function get_subid($db) {
$username= $_SESSION['username']; //variable accessed through the function
$query = $db->query("SELECT userID FROM users where username='$username'");
$row = $query->row(); //Get's the first Row
$result = $row->userID; //Get's the field userID of this first row
return $result;
}
$uID = get_subid($db);
$title = $Result->title;
$desp = $Result->description;
// insert into database
$data = array(
'userID' => $uID,
'title' => $title,
'desp' => $desp
);
$db->insert('saved', $data);
This should be what you'd like (see the comments)