Unable to catch null data properly from mysql - php

I'm trying to catch all data from MySQL to check data already exists or not
if data already exists then it should update else insert new data.
I have 7 to 8 conditions in where clause, some of them are null
now the issue is
when i run query its not catching null column thats why its insert new data instead of updating
below is my code
$fetch_stock = mysqli_query($connection,
"SELECT *
FROM `book_stock`
WHERE book_name = '$book_name'
AND author_id = $book_author
AND author_id1 = $book_author1
AND author_id2 = $book_author2
AND author_id3 = $book_author3
AND author_id4 = $book_author4
AND author_id5 = $book_author5
AND author_id6 = $book_author6"
);
if (mysqli_num_rows($fetch_stock) > 0) {
echo "UPDATE book_stock SET stock_count = stock_count + 1 WHERE book_name = '$book_name' AND author_id = $book_author AND author_id1 = $book_author1 AND author_id2 = $book_author2 AND author_id3 = $book_author3 AND author_id4 = $book_author4 AND author_id5 = $book_author5 AND author_id6 = $book_author6";
mysqli_query($connection,
"UPDATE book_stock
SET stock_count = stock_count + 1
WHERE book_name = '$book_name'
AND author_id = $book_author
AND author_id1 = $book_author1
AND author_id2 = $book_author2
AND author_id3 = $book_author3
AND author_id4 = $book_author4
AND author_id5 = $book_author5
AND author_id6 = $book_author6"
);
} else {
echo "INSERT INTO book_stock (book_name, author_id, author_id1, author_id2, author_id3, author_id4, author_id5, author_id6, stock_count) value ('$book_name', $book_author,$book_author1, $book_author2, $book_author3, $book_author4, $book_author5, $book_author6, 1)";
mysqli_query($connection,
"INSERT INTO book_stock
(book_name, author_id, author_id1, author_id2,
author_id3, author_id4, author_id5, author_id6,
stock_count)
value ('$book_name', $book_author,$book_author1, $book_author2,
$book_author3, $book_author4, $book_author5, $book_author6, 1)");
}
When i print query Its look like this
INSERT INTO book_stock
(book_name, author_id, author_id1, author_id2, author_id3,
author_id4, author_id5, author_id6, stock_count)
value ('cat demo1', 1,2, 3, 4, NULL, NULL, NULL, 1)
I got solution for this from 1 website, which is
$fetch_stock = mysqli_query($connection,
"SELECT *
FROM `book_stock`
WHERE book_name = '$book_name'
AND author_id = $book_author
AND IFNULL(author_id1, 0)= IFNULL($book_author1, 0)
AND IFNULL(author_id2, 0)= IFNULL($book_author2, 0)
AND IFNULL(author_id3, 0)= IFNULL($book_author3, 0)
AND IFNULL(author_id4, 0)= IFNULL($book_author4, 0)
AND IFNULL(author_id5, 0) = IFNULL($book_author5, 0)
AND IFNULL(author_id6, 0) = IFNULL($book_author6, 0)"
);
Its working when i want to display stock.
But i want to do a crud operation by using this logic.
I tried to do from above solution, its work fine but, in db table its update null with 0.
which is not got as per me.
please guide me with best solution.
Thanks

Related

Is it possible to loop through the mysql table rows and check columns?

I have a "matrix" table with the following columns filled in.
matrix_id, user_id, position_1, position_2, position_3
1 1 1982 2251 5841
2 2 6204 0 0
3 3 0 0 0
4 4 0 0 0
I basically want to do the following.
Find a row with the lowest user_id and that has an empty position.
In the example above, that would be user_id 2 and position_2.
I update the row with a query.
I then move on to the next next empty position. Since user_id 2 still has an empty position_3, I update the row again with a query.
Since that row is complete, I move on to the next highest user_Id that has empty positions. In this case, it's user_id 3 and then user_id 4 the one after that.
I know I can do all of the above if I know what the user_id is. But assume in this case, I have no clue what the user_ids are. How would the queries look then?
Here is what I have so far.
$find_user = $db->prepare("SELECT * FROM matrix WHERE user_id > :user_id");
$find_user->bindValue(':user_id', 0);
$find_user->execute();
$result_user = $find_user->fetchAll(PDO::FETCH_ASSOC);
if(count($result_user) > 0) {
foreach($result_user as $row) {
$matrix_id = $row['matrix_id'];
$user_id = $row['user_id'];
$position_1 = $row['position_1'];
$position_2 = $row['position_2'];
$position_3 = $row['position_3'];
}
} else {
$errors[] = 'User Id not found in Matrix.';
}
$update_user = $db->prepare("UPDATE matrix SET position_2 = :position_2 WHERE user_id = :user_id");
$update_user->bindValue(':position_2', 1564;
$update_user->bindParam(':user_id', $user_id);
if($update_user->execute()) {}
This should go through all your users from smallest user_id to largest.
For each user it will check the relevant columns in order and apply a new value to the empty ones.
$new_val = 1999;
$result = $db->query("SELECT * FROM matrix ORDER BY user_id");
$users = $result->fetchAll(PDO::FETCH_ASSOC);
if(count($users) > 0) {
// prepare all the possible queries
// make use of prepare once execute many times
$stmt1 = $db->prepare("UPDATE `matrix` SET `position_1` = :pos WHERE `user_id` = :id");
$stmt2 = $db->prepare("UPDATE `matrix` SET `position_2` = :pos WHERE `user_id` = :id");
$stmt3 = $db->prepare("UPDATE `matrix` SET `position_3` = :pos WHERE `user_id` = :id");
foreach($users as $user) {
if ( $user['$position_1'] == 0 ) {
$stmt1->execute( array(':pos'=>++$new_val,':id'=>$user['user_id']) );
}
if ( $user['$position_2'] == 0 ) {
$stmt1->execute( array(':pos'=>++$new_val,':id'=>$user['user_id']) );
}
if ( $user['$position_3'] == 0 ) {
$stmt1->execute( array(':pos'=>++$new_val,':id'=>$user['user_id']) );
}
}
} else {
$errors[] = 'User Id not found in Matrix.';
}
You could reduce the rows to process by changing the query a bit to only find users with columns to fix
$result = $db->query("SELECT *
FROM matrix
WHERE position_1 = 0
OR position_2 = 0
OR position_3 = 0
ORDER BY user_id");
important thing here, is that you are working with the row, not columns
so check all the prerequisites and update the row.
$find_user = $db->prepare("SELECT * FROM matrix order by user_id asc");
$find_user->execute();
$result_user = $find_user->fetchAll(PDO::FETCH_ASSOC);
foreach($result_user as $row) {
$matrix_id = $row['matrix_id'];
$user_id = $row['user_id'];
$position_1 = $row['position_1'];
$position_2 = $row['position_2'];
$position_3 = $row['position_3'];
}
$str = ''
if (!$position_2){
$str = "position_2 = :position_2"
} else if (!$position_2 && !$position_3){
$str = "position_2 = :position_2 and position_3 = :position_3"
}
$update_user = $db->prepare("UPDATE matrix SET " . $str . " WHERE user_id = :user_id");
$update_user->bindValue(':position_2', 1564);
$update_user->bindValue(':position_3', 1564);
$update_user->bindParam(':user_id', $user_id);
if($update_user->execute()) {}
Also, get all the rows in the matrix table ordered by used_id and process every row, depending on your condition.

Update rows of a SQL table

I have a table with a column called 'status'. The defaut value of 'status' is 0. I want to update the value to '1' after using it.
I basically want to check if the status is 0, if it is, do an operation and then change the value to 1.
Here is the code. All works perfectly except that the value of 0 is not changed to 1.
I am a novice so maybe is a very basic mistake :(
<?php
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$sql = "UPDATE summonerid SET status='1' WHERE status='0';"; // THIS IS THE PART THAT DOES NOT WORK WELL
}
}
}
?>
Any help would be highly appreciated
Try this.. you are not executing the sql statements
$sql = "SELECT number, status FROM summonerid";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$SummonerID = $row["number"];
$status = $row["status"];
if($status=='0'){
$recentgames=$lol->getRecentGames($SummonerID);
$MatchID1=$recentgames->games[0]->gameId;
$sql = "INSERT INTO matchid (number) SELECT * FROM (SELECT '$MatchID1') AS tmp WHERE NOT EXISTS (SELECT number FROM matchid WHERE number = '$MatchID1') LIMIT 1;";
$result1 = $conn->query($sql);
$sql = "UPDATE summonerid SET status='1' WHERE status='0';";
$result1 = $conn->query($sql);
}
}
}
?>

Solve with only one query?

I have the following table:
CREATE TABLE list(
country TINYINT UNSIGNED NOT NULL,
name VARCHAR(10) CHARACTER SET latin1 NOT NULL,
name_index INT UNSIGNED NOT NULL,
UNIQUE KEY(country, name), PRIMARY KEY(country, name_index)) ENGINE = INNODB
I want to:
Given: ($country, $name, $new_index)
Check if a row with country = $country && name = $name exists.
If the row exists, get the index $index = name_index.
If the row doesn't exist, add it and then get the index.
I can do the following using many queries, but I am looking for an efficient way to do it, using only one query. Is this possible?
It's not possible with only one query.
You CAN do this:
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
$sql = "INSERT INTO (your table) (country, name)
VALUES('$country','$name')";
$query = mysql_query($sql);
$check = mysql_num_rows($query);
if($check > 0) {
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
echo "Error occured while trying to insert new row";
}
}
Hope this helps :).

How to update a value by 1 if the new value inserted into the database clashes with value in the database?

I want to update the database of the sort order column to increase its value by one if the the new value inserted into the database clashes with the value that is already in the database. May I know how should I go about doing it? Please help! Thanks!
Below is my code (I am not sure whether am I on the right track):
$result = mysql_query("SELECT sortorder FROM information ORDER BY id ASC;");
if($result >= 1 ){
$i=1;
while ($initialorder = mysql_fetch_assoc($result))
{
$initialorder = $initialorder["sortorder"];
if ($sortorder == $initialorder ){
$result6 = mysql_query("SELECT * FROM information
WHERE `sortorder` = '$sortorder'");
$row6 = mysql_fetch_array($result6);
$removethis1 = $row6['id'];
$result7 = mysql_query("UPDATE information
SET `sortorder`= ((SELECT `sortorder`
FROM (SELECT MAX(`sortorder`) AS
'$initialorder' FROM information) AS '$initialorder') + 1)
WHERE id='$removethis1'");
}
$query = "INSERT INTO `information`
(`id`,`page`,`description`,`status`,`sortorder`,`keyword`,`date_added`)
VALUES
('$id','$title','$description','$status',
'$sortorder','$keyword','$date_added')";
$result = mysql_query($query, $conn);
header('Location: index.php?status=1&title='.$title);
$i++; }
}
You can do this:
INSERT INTO ON `information`
...
DUPLICATE KEY UPDATE
sortorder = '".$sortorder + 1." '

UPDATE mysql_query not updating table

Im having trouble with the UPDATE command.
Im trying to update my db but its just not happening. Ive been trying to get this to work for the last 10 days and its driving me nuts.
Here is the code:
$a = mysql_query("UPDATE `findacab` SET `lat` = ".$ads['Latitude']." , `long` = ".$ads['Longitude']."
WHERE `eeventendtime` = ".$ads['Postcode']." ");
Table:
$q = mysql_query("SELECT Postcode, Latitude, Longitude FROM postcodes");
while($ads = mysql_fetch_array($q))
{
mysql_query("UPDATE findacab SET lat = '".$ads['Latitude']."' , long = '".$ads['Longitude']."' WHERE eeventendtime = '".$ads['Postcode']."' ");
echo $ads['Latitude']." ".$ads['Longitude']." ".$ads['Postcode']."</br>";
//$query = "select count(*) from findacab where eeventendtime = '".mysql_real_escape_string($ads['Postcode'])."'";
}
Unless your complete table consists of only integer you should add quotations around your strings
$a = mysql_query("UPDATE `findacab` SET
`lat` = '".$ads['Latitude']."' ,
`long` = '".$ads['Longitude']."'
WHERE
`eeventendtime` = '".$ads['Postcode']."' ");
$query = "select count(*) from findacab where eeventendtime = '".mysql_real_escape_string($ads['Postcode'])."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row[0]
If it returns 0 then you just don't have records to update.
Another possible reason - you are trying to update table with same values as stored. In this case update will not change the data.

Categories