Mysqli -> num_rows always returns 1 - php

This seems to always return 1 for $item_result->num_rows; even though there are 0 rows in the DB. However, if an item exists it updates the row correctly. I'm sure something is wrong with my syntax but I'm having a hard time wrapping my head around this mysqli.
$item_query = "SELECT COUNT(*) FROM `rel` WHERE `cart_id` = '".$cartId."' && `id_item` = '".$item_id."'";
$item_result = $mysqli->query($item_query) or die($mysqli->error.__LINE__);
if($item_result->num_rows==1) {
$item_query2 = "SELECT * FROM `rel` WHERE `cart_id` = '".$cartId."' && `id_item` = '".$item_id."'";
$item_result2 = $mysqli->query($item_query2) or die($mysqli->error.__LINE__);
$getOldItems = $item_result2->fetch_array();
$oldQty = $getOldItems['amount'];
$oldNotes = $getOldItems['notes'];
$newQty = $oldQty + $item_quantity;
$newNotes = $oldNotes . $item_notes;
$update_qty = $mysqli->query("UPDATE rel SET amount = '$newQty', notes = '$newNotes' WHERE `cart_id` = '$cartId' && `id_item` = '$item_id'");
if(!$update_qty){
printf("Errormessage: %s\n", $mysqli->error);
}
header('Location: ./ordernew.php');
} else {
$insert_cart_item = $mysqli->query("INSERT INTO rel (`email`, `cart_id`, `id_item`, `amount`, `notes`) VALUES ('$email', '$cartId', '$item_id', '$item_quantity', '$item_notes')");
if(!$insert_cart_item) {
printf("Errormessage: %s\n", $mysqli->error);
}
header('Location: ./ordernew.php');
}

When you do SELECT COUNT(*) there will always be at least one result. Even if its 0.
You will need to fetch the result of the query to get the correct count.

Related

SQL update & insert

I have a MYSQL table named issues_tot including following columns:
v_code, oid, amount, mod_date
02) Then I need to update or insert records of the table according to the given condition as follows:
if(($vt == $vote)||($of == $ono)){
03) update is working properly, but insert is not (else part). My code is showing below:
if (isset($_POST["submit"]))
{
$ono =$_POST["oid"];
$amt =$_POST["amt"];
$allo=mysql_fetch_array(mysql_query("SELECT * FROM allocation WHERE al_code='{$_GET['al_code']}'"));
$vote=$allo['v_code'];
$current_date = date("Y-m-d H:i:s");
$query ="select * from issues_tot where v_code='$vote' ";
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
$vt = $row['v_code'] ;
$of = $row['oid'] ;
if(($vt == $vote)||($of == $ono)){
$query ="UPDATE issues_tot SET oid = $ono, amount = amount + $amt WHERE v_code=$vote";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}else {
$query ="INSERT INTO issues_tot (v_code, oid, amount, mod_date) VALUES ('$vote', '$ono', '$amt', '$current_date')";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}
}
I can not understand what I am going wrong. Can anyone help me ?. Pls

Sending information from a newly created record to a different MySQL table

I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else

PHP / MySQL - Write and check UPPERCASE in database

I have the following code to write the name and score of a player into a highscore table. How can I write the 'name' in uppercase into the database?
if(isset($_GET['name']) && isset($_GET['score'])) {
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['score']));
$checkExist = mysql_query("SELECT `name`, `score` FROM `$tbl_name` WHERE `name` = '$name'");
$row = mysql_fetch_assoc($checkExist);
if (mysql_num_rows($checkExist) > 0){
if ($score > $row['score']){
$sql = mysql_query("UPDATE `$tbl_name` SET `score` = '$score' WHERE `name` = '$name'");
} else {
// ERROR MSG: Your new score is lower.(not updating the database)
}
} else {
$sql = mysql_query("INSERT INTO `$tbl_name` (`id`,`name`,`score`) VALUES ('','$name','$score');");
}
$name = strtoupper(strip_tags(mysql_real_escape_string($_GET['name'])));
http://php.net/manual/en/function.strtoupper.php
Either use strtoupper() in PHP, or UPPER() in MySQL: both do exactly the same, it's up to you.

how to converting mysql into mysqli

i have the following problem with a login script. at the moment i refresh my site and would like to change mysql into mysqli. i have a working code, that works with mysql like it should to. now i get in trouble with changing that into mysqli, which doesn't work.
here is the original mysql code:
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
session_register('id');
$_SESSION['id'] = $id;
mysql_query("UPDATE tableA SET time=now(), x4=x4 + 1 WHERE id='$id'");
mysql_query("DELETE FROM tableB WHERE (NOW() - INTERVAL 1 DAY) > Date AND ID='$id'");
$result = mysql_query("SELECT COUNT(*) AS val FROM tableB WHERE ID='$id'");
$count = mysql_fetch_assoc($result);
var_dump($count);
if ($count [val] <xy){
mysql_query("INSERT INTO tableB (Date, ID) VALUES (now(),'$id') ");
mysql_query("UPDATE tableA SET x7=x7 + 1 WHERE id='$id'");
and here is the mysqli version, that wont work and i dont know why:
$time = gmdate("M d Y H:i:s", time());
$id = '".$row["id"]."';
$get_id = "SELECT id FROM tableA WHERE x1='".$x1."' AND x2='".$x2."'";
$result = mysqli_query($db, $get_id);
if ($result === false) {
printf("Errormessage 1");
exit();
}
$row = $result->fetch_array(MYSQLI_ASSOC);
$update = "UPDATE tableA SET time=now(), x4=x4 + 1 WHERE id='".$row["id"]."'";
$result2 = mysqli_query($db, $update);
if ($result2 === false) {
printf("Errormessage 2");
exit();
}
$reset = "DELETE FROM tableB WHERE (NOW() - INTERVAL 1 DAY) > Date AND ID='".$row["id"]."'";
$result3 = mysqli_query($db, $reset);
if ($result3 === false) {
printf("Errormessage 4");
exit();
}
$count = "SELECT COUNT(*) AS val FROM tableB WHERE ID='".$row["id"]."'";
$result4 = mysqli_query($db, $count);
if ($result4 === false) {
printf("Errormessage 5");
exit();
}
$sum = $result4->fetch_assoc($count);
var_dump($sum);
if ($count [val] <xy){
$insert = "INSERT INTO TableB (Date, ID) VALUES(?,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('ss', $time, $id);
$query->execute();
$update_x = "UPDATE tableA SET x7=x7 + 1 WHERE id='".$row["id"]."'";
$result5 = mysqli_query($db, $update_x);
if ($result5 === false) {
printf("Errormessage 5");
exit();
You haven't mentioned the actual error but it seems that problem occurs from here:
$row = $result->fetch_array(MYSQLI_ASSOC);
you didnot use a loop here like your mysql version of code.
You are attempting to insert $time into what appears to be a DATETIME column, based on your old mysql version, but it is improperly formatted.
$time = gmdate("M d Y H:i:s", time());
Based on your use of NOW() in the old code, we assume TableB.Date to be a DATETIME type:
mysql_query("INSERT INTO tableB (Date, ID) VALUES (now(),'$id') ");
So in your new code, since you don't use NOW() for the TableB insert, you should be creating $time as YYYY-MM-DD:
// Should be YYYY-MM-DDD H:i:s for MySQL
$time = gmdate("Y-m-d H:i:s", time());
// It gets inserted into TableB here
$insert = "INSERT INTO TableB (Date, ID) VALUES(?,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('ss', $time, $id);
$query->execute();
Or, just use MySQL's NOW() in the new code unless you have a reason to specify the time in PHP code:
$insert = "INSERT INTO TableB (Date, ID) VALUES(NOW() ,?) ";
if($query = $db->prepare($insert)){
$query->bind_param('s', $id);
$query->execute();

PHP/MySQL Update and Insert based on two tables

I have been going over this for a few days now and keep reaching stumbling blocks. I am trying to select a unique id from table2 and match it against an id in table1. If the id is matched, update the row in table1 and remove the record from table2. If there is no match then insert the record into table1.
I have got to a point where I can update the records and insert the new ones but I cannot seem to delete the matched record before the insert therefore creating a duplicate. I have tried a delete join query after the update but because the new logon_id has a character prepended to it, it no longer matches in table2.
I was doing an update join before for updates but I had too many queries going on so trying to keep it simple.
Any advice? Still a newb at this game.
$table2_query = "SELECT * FROM table2";
$table2_result = mysql_query($table2_query);
$table2_count = mysql_num_rows($table2_result);
if($table2_count == 0) {
if(mysql_error()) {
echo 'Error: '.mysql_error();
}
}
while($table2_row = mysql_fetch_array($table2_result, MYSQL_ASSOC)) {
$check_number_length = strlen($table2_row['unique_id']);
if($check_number_length < 7) {
if(substr($table2_row['unique_id'], 0, 2) < 35) {
$logon_id = 'n' . $table2_row['unique_id'];
}else {
$logon_id = 'v' . $table2_row['unique_id'];
}
}else {
$logon_id = $table2_row['unique_id'];
}
// Set variables for insert query for creation of a new user record
$first_name = $table2_row['firstname'];
$last_name = $table2_row['lastname'];
$email_address = $table2_row['email'];
$duplicates_query = "SELECT * FROM table1 WHERE '$logon_id' = logon_id";
$duplicates_result = mysql_query($duplicates_query);
$duplicates_row = mysql_fetch_array($duplicates_result);
$duplicates_count = mysql_num_rows($duplicates_result);
if($duplicates_count == 0) {
if(mysql_error()) {
echo 'Error: '.mysql_error();
}
}else {
$update_records_query = "UPDATE table1 SET first_name='$first_name', last_name='$last_name', email_address='$email_address'";
$update_records_result = mysql_query($update_records_query);
$update_records_count = mysql_affected_rows();
echo $update_records_count;
}
$create_records_query = "INSERT INTO table1 (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
$create_records_result = mysql_query($create_records_query);
$create_records_count = mysql_affected_rows();
if($create_records_count == 0){
if(mysql_error()){
echo 'Error: '.mysql_error();
}
}
echo $create_records_count . ' record(s) created.';
}
$res = mysql_query ("SELECT count(table1.login_id) AS count FROM table2 LEFT JOIN table1 ON table2.login_id = table1.login_id WHERE table2.login_id = \"".$login_id."\";") or die ("Error joining tables");
/*joins both tables together and selects both id's from tables */
$row = mysql_fetch_assoc($res); // should only return one row so grab first
if ($row['count'] > 0) { // check if id exists in both tables (duplicates)
// updates rows from one table into another
mysql_query('UPDATE table1,table2 SET table1.username = table2.username, table1.password = table2.password, table1.email = table2.email WHERE table1.login_id = "'.$login_id.'" AND table2.login_id = "'.$login_id.'";') or die ("error updating table1");
//delete old row
mysql_query('DELETE FROM table2 WHERE login_id = "'.$login_id.'";') or die("error deleting from table2");
}else { // if id doesn't exist in table1
mysql_query ("INSERT INTO table1(username,password,email) SELECT username,password,email FROM table2 where login_id = '".$login_id."';") or die ("error inserting into table1");
}
remove the n at the beginning of login_id on table1
UPDATE table1 set login_id = replace(login_id,"n","");
new update query if remove n at begin of login_id
mysql_query ('UPDATE table1,table2 SET table1.username = table2.username, table1.password = table2.password, table1.email = table2.email WHERE table1.login_id = table2.login_id AND table1.login_id = "'.$login_id.'";');

Categories