double data on mysql - php

I use the php operator && to select multiple data so that there is no duplication on mysql.
Does the code that I use below run fine? Is there a more simple use of PHP operators?
$date= date('Y/m/d');
$cekcount = mysql_num_rows(mysql_query("SELECT * FROM `pending_media` where `mediaid`='$dielz'"));
$cekcount2 = mysql_num_rows(mysql_query("SELECT * FROM `media` where `mediaid`='$dielz'"));
$selectcount = mysql_query("SELECT * FROM `media` where `date`='$date' AND `uplink`='$nam'");
$cekcount3 = mysql_num_rows($selectcount);
if($cekcount == 0 && $cekcount2 == 0 && $cekcount3 == 0){
mysql_query("INSERT INTO pending_media VALUES('','$nam','$dielz')");

Upgrade to mysqli, I'll recommend object-oriented syntax because it is nicer to work with.
In accordance with the best practice of "minimize calls to the database", I'll condense your three queries into a single, united SELECT call then check for a non-0 result.
My untested suggestion using mysqli's object-oriented syntax (I did test the SELECT query in PHPMyAdmin):
$query = "SELECT SUM(tally)
FROM (
SELECT COUNT(*) AS tally
FROM pending_media
WHERE mediaid = ?
UNION ALL
SELECT COUNT(*)
FROM media
WHERE mediaid = ? OR (date = ? AND uplink = ?)
) t";
$conn = new mysqli("localhost", "root","","dbname");
$stmt = $conn->prepare($query);
$stmt->bind_param("ssss", $dielz, $dielz, $date, $nam);
$stmt->execute();
$stmt->bind_result($tally);
$stmt->fetch();
if (!$tally) {
$stmt->close();
// insert qualifying data
$stmt = $conn->prepare("INSERT INTO pending_media VALUES ('',?,?)");
$stmt->bind_param("ss", $nam, $dielz);
if ($stmt->execute()) {
echo "Insert Query Error"; // $stmt->error;
}else{
echo "Success";
}
}

Related

Prepared Statements Mysql not working

I am trying to use prepared statements to select data from a table as the following. This method does not work.
$sql = "SELECT * FROM `usrs` WHERE `username` = ? ";
$statement = $this->conn->prepare($sql);
if (!statement)
{
throw new Exception($statement->error);
}
$statement->bind_param("s",$username);
$returnValue = $statement->execute();
return $returnValue;
$sql should be in the following format.
$sql = "SELECT * FROM `usrs` WHERE `username` = 'username' ";
however the above code does not place single quotes ' ' around username
I need to place username between two single quotes ' ' as shown. if I use just
$sql = "SELECT * FROM `usrs` WHERE `username` = username "
it does not work.
any suggesstions how to do that.
Read this carefully:
bool mysqli_stmt::execute ( void )
it means it returns boolean - that is not a usable object or an array.
You've to fetch the statement.
Here's the fix:
$sql = "SELECT * FROM `usrs` WHERE `username` = ? LIMIT 1";
$statement = $this->conn->prepare($sql);
$statement->bind_param("s",$username);
if ($statement->execute()) {
$result = $statement->get_result();
return $result->fetch_assoc();
}
return null;
P.S. Thank You #Phil for fixing my mistakes in my answer

Php: fetching last inserted row on mysql table to use for another mysql statement

I need to fetch the id of the last inserted row from a mysql table using php and use that id to enter a new entry on another table. I have this until now
$inductionmethod = $_POST['inductionmethod'];
$injectionmethod = $_POST['injectionmethod'];
$dosage = $_POST['dosage'];
$metric = $_POST['metric'];
$notes = $_POST['notes'];
global $db_usr;
$query = "SELECT MAX( experiment_id ) FROM experiment";
$prep = $db_usr->prepare($query);
$lastid = $prep->fetch();
$query ="INSERT INTO experiment_using_methods (experiment_id, induction_method, injection_method, dosage_quantity, dosage_unit, dosage_qualitative)
VALUES (
'".$lastid['MAX( experiment_id )']."', # the fetched ID of the corresponding dataset
(SELECT induction_method_id FROM induction_method WHERE im_name = '".$inductionmethod."'), # name of induction method
(SELECT injection_method_id FROM injection_method WHERE im_name = '".$injectionmethod."'), # name of the injection method
'".floatval($dosage)."', # dosage quantity
'".$metric."', # dosage unit or metric
'".$notes."' # qualitative dosage - REMOVE??
)";
$prep = $db_usr->prepare($query);
$prep->execute();
I think I'm getting an error while fetching the MAX( experiment_id) or maybe I'm using it incorrectly on the INSERT statement because if I replace the ".$lastid['MAX( experiment_id )']." part by a number the insert statement works fine. On the other hand I also test the SELECT MAX( experiment_id ) FROM experiment statement on the mysql command line and it also works fine. Am I using fetch and referencing the result value correctly?
Thing this is the main issue:
$prep = $db_usr->prepare($query);
$lastid = $prep->fetch();
change it to:
$prep = $db_usr->prepare($query);
$prep->execute();
$lastid = $prep->fetch();
If you have connection as $con, then for MySQLi Object-oriented:
if ($con->query($sql) === TRUE) {
$last_id = $conn->insert_id;
}
MySQLi Procedural way:
if (mysqli_query($con, $sql)) {
$last_id = mysqli_insert_id($con);
}
PDO way:
$con->exec($sql);
$last_id = $con->lastInsertId();

Convert sql to mysqli_prepare with variable variables

I'm having trouble to convert my code from sql to mysqli. $XX can be 1 or 0. When $XX=1 I want to search for it. When $XX=0, there must be no search for $XX. Same for $YY.
Old code
$sql = "SELECT name FROM tabel WHERE 1=1";
if (!empty($XX)) {$sql .= " AND XX = 1 ";}
if (!empty($YY)) {$sql .= " AND YY = 1 ";}
When $XX=1 and $YY=1, the code will look like:
$sql = "SELECT name FROM tabel WHERE 1=1 AND XX = 1 AND YY = 1";
When $XX=0 and $YY=1, the code will look like:
$sql = "SELECT name FROM tabel WHERE 1=1 AND YY = 1";
When $XX=0 and $YY=0, the code will look like:
$sql = "SELECT name FROM tabel WHERE 1=1";
The 'problem' is that I do not want to search for XX=0 because that excludes all XX=1 answers. When XX=0, it should not search for XX.
New code
$stmt = mysqli_prepare($link, "SELECT name FROM tabel WHERE XX=? and YY=?");
mysqli_stmt_bind_param($stmt, "ii", $XX, $YY);
Who knows how the mysqli code must look like? Thanks!
EDIT
Okay, from what I get now, it should be simple. If the only possible value for XX and YY in the query is 1, you don't need bind_param.
$qry = 'SELECT name FROM table WHERE 1=1';
$qry .= (!empty($XX)) ? ' AND XX=1';
$qry .= (!empty($YY)) ? ' AND YY=1';
$stmt = mysqli_prepare($link, $qry);
And then just execute your query.
You can rewrite the query in the following way
SELECT * FROM table1 WHERE (xx = ? OR ? = 0) AND (yy = ? OR ? = 0)
Here is SQLFiddle demo
$sql = "SELECT * FROM table1 WHERE (xx = ? OR ? = 0) AND (yy = ? OR ? = 0)";
$db = new mysqli(...);
$stmt = $db->prepare($sql)) {
$stmt->bind_param('iiii', $xx, $xx, $yy, $yy);
$stmt->execute();
$stmt->bind_result(...);
another alternate if you can pass the field name as parameter
$stmt = mysqli_prepare($link, "SELECT name FROM tabel WHERE XX=? and YY=?");
mysqli_stmt_bind_param($stmt, "ii", $XX, $YY);
if you want to avoid filtering XX pass $XX as 'XX'(i.e field name) insted of 0
In such a special case when no variable is actually going into query, you can stick to your current setup. Just change prepare and bind to mysqli_query().
However, in case you need to add a variable into query, you either can use peterm's dirty solution or create the conditional query with placeholders and then call bind_param() with variable number of parameters using call_user_func_array()

SELECT and INSERT/UPDATE within the same query using mysqli

I am wandering if it is possible to first SELECT and if not true INSERT into db within the same query using mysqli?
Here is how I do i now:
$sel_timestamp = mktime(0, 0, 0, date("n"), date("j")-$day, date("Y"));
$sel_tag = date("Y-m-d",$sel_timestamp);
$user = 1;
if ($result = $mysqli->query("SELECT * FROM ".$prefix."_active_users WHERE userid = $user AND DATE(timestamp) = '$sel_tag'")){
if($result->num_rows < 1){
$insert = "INSERT INTO ".$prefix."_active_users (userid,timestamp) VALUES (?,?)";
$stmt = $mysqli->stmt_init();
if($stmt->prepare($insert)){
$stmt->bind_param('is', $user,$sel_tag);
$stmt->execute();
$stmt->close();
}
}
$result->close();
}
In my case I use 2 queries, but is it possible to merge this into one?
Thanks in advance!
if you have a UNIQUE KEY on (userid,timestamp), then you can use
INSERT IGNORE INTO ".$prefix."_active_users (userid,timestamp) VALUES (?,?)
IGNORE is a key word
However, you can leave your current code as is. Nothing wrong with having 2 queries too.

WHERE statement inside if condition in SQL

Can I do a WHERE clause inside an IF statement?
Like I want something like this:
$SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC");
$rows = mysql_fetch_array($SQL);
$email = $_SESSION['email_of_user'];
if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email)
Edit Server
<?php else : ?>
Add Server
<?php endif; ?>
Do I need (" where the WHERE statement is? Because I tried that and it didn't seem to work...
Or can I do it with an if condition inside of a where clause? Not sure of all these terms yet so correct me if I'm wrong...
You cannot mix up a query statement with PHP's statement. Instead write a query extracting desired results and check if there are any rows from that query.
I will show you an example:
$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query
$result = mysqli_query($query, $link); //Query the server
if(mysqli_num_rows($result)) { //Check if there are rows
$authenticated = true; //if there is, set a boolean variable to denote the authentication
}
//Then do what you want
if($authenticated) {
echo "Edit Server";
} else {
echo "Add Server";
}
Since Aaron has shown such a effort to encourage safe code in my example. Here is how you can do this securely. PDO Library provides options to bind params to the query statement in the safe way. So, here is how to do it.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection
//Create the Query Statemetn
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email');
//Binds Parameters in the safe way
$sth -> bindParam(':field', 1, PDO::PARAM_INT);
$sth -> bindParam(':email', $email, PDO::PARAM_STRING);
//Then Execute the statement
$sth->execute();
$result = $sth->fetchAll(); //This returns the result set as an associative array

Categories