here is a simple mysqli query to select specific records from my mysql database:
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
}
The question is:
How can I get (best practices) all the other records, which will not be selected with this query filter?
It can be like
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
$query2 = "select * from 'myTable' WHERE 'bookid' != ".$zeile['ID']."'";
$result2 = $db -> query($query2);
// do something...
}
}
OR
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
$query2 = "select * from 'myTable' WHERE 'bookid' != '".$data['ID']."'";
$result2 = $db -> query($query2);
while($zeile2 = $result2-> fetch_object()){
// do something...
}
}
Running successive, more or less identical, queries in a loop is fundamentally a bad way to do things. Create a list of $data['ID'] values you want to work with, then use one query to retrieve all the rows IN that list, and a second query to retrieve everything NOT IN that list:
Important: This code assumes that the values in $getData[]['ID'] can be trusted. i.e. they have been validated before entry to this code, or they come from a trusted source.
// Create a list:
$inList = '('.implode(',', array_column($getData, 'ID')).')';
$sqlIn = "SELECT * FROM `myTable` WHERE `bookid` IN $inList";
// run the query. Check for errors
if (($result = $db->query( $sqlIn )) === false) {
throw new Exception($db->error);
}
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
// Now use the same list to exclude those rows
$sqlOut = "SELECT * FROM `myTable` WHERE `bookid` NOT IN $inList";
// run the query. Check for errors
if (($result = $db->query( $sqlOut )) === false) {
throw new Exception($db->error);
}
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
Related
how to check resulted row values from while loop are same,I need to update when status is completed from all results...
$result = $db->query("SELECT * FROM fy_working_staf_cstm WHERE task_id_c='".$t_id."'");
while($row = $db->fetchRow($result)){
++$tas;
$staff_id=$row['id_c'];
$result1 = $db->query("SELECT `status` FROM `fy_working_staf` WHERE id='".$staff_id."' AND `status`='Completed'");
$staf = $db->fetchByAssoc($result1);
$status = $staf['status'];
if($stat=='Completed')
{
++$tas1;
//$comple_staus='Closed_Closed';
}
}
if(($tas == $tas1) && ($tas1 !=0) )
{
$q = $db->query("UPDATE `tasks` SET `status`='Completed' WHERE id='".$t_id."' ");
$st = $db->fetchByAssoc($q);
}
Instead i can use break condition in this as :
while($row = $db->fetchRow($result)){
$staff_id=$row['id_c'];
$result1 = $db->query("SELECT `status` FROM `fy_working_staf` WHERE id='".$staff_id."' AND `status`='Completed'");
$staf = $db->fetchByAssoc($result1);
$status = $staf['status'];
if($stat!='Completed')
{
$comple_staus='Closed_Closed';
break;// will exit the loop when the row is not same
}
}
I'm having a hard time getting this search results with pagination code to work. It does successfully grab the search keyword entered in the html form on another page and brings it into this search.php page. if I echo $search I see the keyword on the page. But I get no results even though I should for the query. Can anyone see what might be going on?
require "PDO_Pagination.php";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.genre = $search");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories WHERE stories.genre = $search ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
else
{
$pagination->rowCount("SELECT * FROM stories");
$pagination->config(3, 5);
$sql = "SELECT * FROM stories ORDER BY SID ASC LIMIT $pagination->start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
$model[] = $rows;
}
}
$query = "SELECT * FROM stories";
if(isset($_REQUEST["search_text"]) && $_REQUEST["search_text"] != "")
{
$search = htmlspecialchars($_REQUEST["search_text"]);
$pagination->param = "&search=$search";
$query .= " WHERE genre LIKE '%$search%'";
}
// No need for else statement.
$pagination->rowCount($query);
$pagination->config(3, 5);
$query .= " ORDER BY SID ASC LIMIT {$pagination->start_row}, {$pagination->max_rows}";
$stmt = $connection->prepare($query);
$stmt->execute();
$model = $stmt->fetchAll();
var_dump($model);
In your query do:
WHERE stories.genre LIKE '%string%');
instead of:
WHERE stories.genre = 'string');
Because the equals will want to literally equal the field.
In fact I am working on a small PHP script but I am facing a problem right now.The problem is that i want to check if my query return records this is my mysqli query:
$sql = "select * from specs where btitleid=$id and phoneid=$aydi"
$check = $conn->query($sql)
while($row = $check->fetch_assoc()) {$tocheck = $row['content'];}
I don't want to check the number of rows of this query to see if it is null.I want to check if all $row['content'] are empty.
How about this:
$sql = "select * from specs where btitleid=$id and phoneid=$aydi";
$check = $conn->query($sql);
$contentAllEmpty = true;
while ($row = $check->fetch_assoc()) {
if (strlen($row['content']) > 0) {
$contentAllEmpty = false;
}
}
if ($contentAllEmpty) {
//do something
}
use ==
while ($row = $check->fetch_assoc()) {
if ($row['content'] == '') {
... code here
}
}
To get back only records where the content column is not empty -
$sql = "SELECT * FROM `specs` WHERE `btitleid` = $id AND `phoneid` = $aydi AND (`content` IS NOT NULL OR `content` != '') ";
I am attempting to insert records for Artists, Songs and Record Labels, whilst checking that the data does not already exist in the Database.
The following code is from Mike Fenwick.
<?php
$query = "SELECT id FROM table WHERE unique1=value1 AND unique2=value2…";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET unique1=value1 AND unique2=value2…";
$insert_result = mysql_query($query);
$id = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$id = $row['id'];
}
return $id;
?>
I need to modify this to check if three unique values exist already (from 3 separate tables), and if not, insert them. Here is my attempt:
<?php
$query = "SELECT id FROM artistsTable WHERE artistName='Beyonce'";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET artistName='Beyonce' AND artistImage='beyonce.jpg'";
$insert_result = mysql_query($query);
$artistID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$artistID = $row['artistID'];
}
return $artistID;
$query = "SELECT id FROM recordLabelTable WHERE labelName='Columbia Records'";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET labelName='Columbia Records'";
$insert_result = mysql_query($query);
$labelID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$labelID = $row['labelID'];
}
return $labelID;
$query = "SELECT id FROM songTable WHERE trackTitle='Crazy in Love' AND artistID=".$artistID." AND labelID=".$labelID."";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO songTable SET trackTitle='Crazy in Love' AND artistID=".$artistID." AND labelID=".$labelID."";
$insert_result = mysql_query($query);
$songID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$songID = $row['songID'];
}
return $songID;
?>
I'm assuming that there must be a more efficient way to do this. Any ideas would be much appreciated.
Using basic inset / ignore syntax you could do something like this.
A couple of inserts to put in the artist details and label details, then an INSERT based on a SELECT:-
<?php
$query = "INSERT IGNORE INTO artistTable (artistName, artistImag) VALUES('Beyonce', 'beyonce.jpg')";
$insert_result = mysql_query($query);
$query = "INSERT IGNORE INTO labelTable (labelName) VALUES('Columbia Records')";
$insert_result = mysql_query($query);
$query = "INSERT IGNORE INTO songTable (trackTitle, artistID, labelID)
SELECT 'Crazy in Love', a.artistID, b.labelID
FROM artistTable a
INNER JOIN labelTable b
ON a.artistName = 'Beyonce'
AND a.artistImag = 'beyonce.jpg'
AND b.labelName = 'Columbia Records'";
$insert_result = mysql_query($query);
$songID = mysql_insert_id();
return $songID;
?>
As #LoganWayne says, you probably should use MySQLi .
<?php
/* ESTABLISH CONNECTION */
$con=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* FOR artistsTable TABLE */
$query = "SELECT id FROM artistsTable WHERE artistName='Beyonce'";
$select_result = mysqli_query($con,$query); /* EXECUTE QUERY */
if (mysqli_num_rows($select_result)==0) { /* IF QUERY'S RESULT IS 0 */
$query = "INSERT INTO table SET artistName='Beyonce' AND artistImage='beyonce.jpg'";
$insert_result = mysqli_query($con,$query); /* EXECUTE INSERT QUERY */
} /* END OF IF */
else {
while($row = mysqli_fetch_array($select_result)){
$artistID = mysqli_real_escape_string($con,$row['artistID']); /* ESCAPE STRING */
} /* END OF WHILE LOOP */
} /* END OF ELSE */
/* FOR recordLabelTable TABLE */
$query = "SELECT id FROM recordLabelTable WHERE labelName='Columbia Records'";
$select_result = mysqli_query($con,$query); /* EXECUTE SELECT QUERY */
if (mysqli_num_rows($select_result)==0) { /* IF QUERY'S RESULT IS 0 */
$query = "INSERT INTO table SET labelName='Columbia Records'";
$insert_result = mysqli_query($con,$query); /* EXECUTE INSERT QUERY */
}
else {
while($row = mysqli_fetch_array($select_result)){
$labelID = mysqli_real_escape_string($con,$row['labelID']); /* ESCAPE STRING */
}
}
/* FOR songtable TABLE */
$query = "SELECT id FROM songTable WHERE trackTitle='Crazy in Love' AND artistID='$artistID' AND labelID='$labelID'";
$select_result = mysqli_query($con,$query); /* EXECUTE SELECT QUERY */
if (mysqli_num_rows($select_result)==0) {
$query = "INSERT INTO songTable SET trackTitle='Crazy in Love' AND artistID='$artistID' AND labelID='$labelID'";
$insert_result = mysqli_query($con,$query); /* EXECUTE QUERY */
} /* END OF IF */
else {
while($row = mysqli_fetch_array($select_result)){
$songID = mysqli_real_escape_string($con,$row['songID']);
} /* END OF WHILE LOOP */
}
?>
SUMMARY:
Used at least MySQLi instead of deprecated MySQL.
Replaced fetch_assoc() function with fetch_array() function.
Used mysqli_real_escape_string() function to prevent some of SQL injections.
Cleaned your code. You have misplaced apostrophes(') and double quotes(") hanging around.
Script searchs through DB and fix broken links. Search and replace functionality works fine, but when trying to save updated data scripts wrights only first raw. I'm stucked! I can use simple mysql_query commands to update data, but needs PDO...
header('Content-Type: text/html; charset=UTF-8');
error_reporting(E_ALL);
echo "Welcome";
$mysql = new PDO('mysql:host=localhost;dbname=db_name;charset=UTF-8','user','12345');
if (!$mysql) die('Can\'t connect');
$tables = array(
'categories',
'news',
'pages'
);
function getContent($table) {
global $mysql;
$fieldnum = 0;
$fields = array();
$vals = array();
$st = $mysql->query("SHOW FIELDS FROM `{$table}`");
while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
$fields[$fieldnum]=$row["Field"];
$fieldnum++;
}
$totalfields=$fieldnum;
$res = $mysql->query("SELECT * FROM `{$table}`");
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
while ($row = $res->fetch(PDO::FETCH_NUM)) {
for ($j=0; $j<$res->columnCount();$j++) {
$rs = str_replace('index.php/','',$row[$j],$m);
if ($rs && $m>0) {
if ($table == 'categories')
$prim= 'cat_id';
elseif($table == 'news') $prim= 'news_id';
elseif($table == 'pages') $prim= 'page_id';
else $prim= $table.'_id';
$upd = $mysql->prepare($sql);
$update = $upd->execute(array(
':table'=>$table,
':field'=>$fields[$j],
':val'=>$rs,
':idf'=>$prim,
':id'=>$row[0]
));
}
}
}
}
foreach ($tables as $t) {
getContent($t);
}
Need help to fix it!
try to fetch all and then go through array
and you do not need to use prepare every time - just once see Example #2
....
$res = $mysql->query("SELECT * FROM `{$table}`");
$rows = $res->fetchAll(PDO::FETCH_NUM);
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
$upd = $mysql->prepare($sql);
foreach ($rows as $row) {
foreach ($row as $col_name => $value) {
......
prepare outside the loop! you are loosing its value this way, also try $upd->debugDumpParams(); and binding before execution, maybe the values u r binding is not right.