How can i escape MySQL 'Unable to jump row 0' error? - php

My question is how can I be sure of a row that I'd like to return is exists? I don't want to suppress it with PHP's # option or count rows before every query to find out the row is exists or not.
So there's a simple query like this:
"SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
and the table cannot contain the row with id 234.

You don't have to count rows before every query - generally you do it after.
What about something like this
$query = "SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
// do something because it was found
}

You're probably using mysql_result() to fetch the fields. Consider mysql_fetch_array instead. It returns FALSE if there are no more rows to fetch.
<?php
$mysql = mysql_connect('..', '..', '..') or die(mysql_error());
mysql_select_db('..', $mysql) or die(mysql_error());
$query = "SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
$result = mysql_query($query, $mysql) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo 'no such record';
}
else {
echo $row['title'], ' ', $row['id'];
}

Related

PHP MySQL Query with NOT LIKE specific id

I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .
DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED
Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);
Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');

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 :).

process sql query results

I got a table named "Serials" with 5 comumns
Serial, Code, Name, Redeemed, Redeem_date
i am selecting some fields from that table with this query:
$query = "SELECT `Name`,`Redeemed`,`Redeem_date` FROM `Serials` WHERE `Serial` = '$serial' AND `Code` = '$code'";
$db->setQuery($query);
$db->query();
But i dont know how to pass these values in the following variables so i can use them in if statements later
$name= //retured value from column Name
$redeemed= //retured value from column Redeemed
$redeem_date= //retured value from column Redeem_date
just like this..
// Your query here..
$query = "SELECT `Name`,`Redeemed`,`Redeem_date` FROM `Serials` WHERE `Serial` = '$serial' AND `Code` = '$code'";
$db->setQuery($query);
$results = $db->query();
//fetch data and stored into variables
while($row = fetch_array($results)){
$name = $row['Name'];
$redeemed = $row['Redeemed'];
$redeem_date = $row['Redeem_date'];
}
try something like this :
<?php
$result = $db->query("SELECT `Name`,`Redeemed`,`Redeem_date` FROM `Serials` WHERE `Serial` = '$serial' AND `Code` = '$code'");
while (list($name, $redeemed, $redeem_date) = $result->fetch(PDO::FETCH_NUM)) {
// DO SOMETHING
}
?>
while ($row = $db->fetch()) {
$name= $row['name'];
$redeemed= $row['redeemed'];
$redeem_date= $row['redeem_date'];
}
this one might fetch your results and assign to vars

Running more than one Mysql Query using PHP

I am needing to run more than one Mysql Query using PHP. I have a site and pull all the information from the databse
$sql = "SELECT * FROM $table WHERE ID=$escape";
$query = mysql_query($sql) or die(mysql_error());
$rentals = mysql_fetch_assoc($query);
Now I have two other queries I need to also run for Previous and Next Buttons
$sqlPrev = 'SELECT `id` FROM `table`
WHERE `id` < '$curId' AND `catId` = '$curCat'
ORDER BY `id` DESC LIMIT 1;
$sqlNext = 'SELECT `id` FROM `table`
WHERE `id` > '$curId' AND `catId` = '$curCat'
ORDER BY `id` ASC LIMIT 1;
I have the coding right when I run these in PHP MyAdmin, however when I try to execute them via the website I get a mysql error!
Problems are the " instead of ' at $sqlPrev and $sqlNext. {$curID} only works with "".
And there's no end " or '.
mysql_query can only execute one query at a time.
Basically you just need to have 3 calls to mysql_query.
$sql = "SELECT * FROM $table WHERE ID=$escape";
$query = mysql_query($sql) or die(mysql_error());
$rentals = mysql_fetch_assoc($query);
$sqlPrev = 'SELECT `id` FROM `table`
WHERE `id` < ' . $curId . ' AND `catId` = ' . $curCat . '
ORDER BY `id` DESC LIMIT 1';
$sqlNext = 'SELECT `id` FROM `table`
WHERE `id` > ' . $curId . ' AND `catId` = ' . $curCat . '
ORDER BY `id` ASC LIMIT 1';
$resultPrev = mysql_query($sqlPrev);
$resultNext = mysql_query($sqlNext);
// todo: check that the above queries executed successfully
// if (!$resultPrev) echo mysql_error();
if (mysql_num_rows($resultPrev)) {
$prev = mysql_fetch_array($resultPrev);
$prevId = $prev['id'];
} else {
$prevId = null; // there is no previous item
}
if (mysql_num_rows($resultNext)) {
$next = mysql_fetch_array($resultNext);
$nextId = $next['id'];
} else {
$nextId = null; // there is no next item
}
You probably need to add the concatenation operator (.) between the string literals and the variables. (It's required in Perl; I do the same thing in PHP.)
$sqlPrev = 'SELECT `id` FROM `table`
WHERE `id` < '.$curId.' AND `catId` = '.$curCat.'
ORDER BY `id` DESC LIMIT 1';
Echo the SQL text that is being sent to the database. That will reveal the problem.
For more than one query, you need to use multi query or close the result before calling another query. For example if you write in the object oriented style.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM mytable";
$result=$conn->query($sql);
echo $result->num_rows;
$sql="SELECT id FROM mytable";
$result2=$conn->query($sql);
echo $result2->num_rows; // does not work because result was not closed.
To get it to work, write this instead.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM mytable";
$result=$conn->query($sql);
echo $result->num_rows;
$result->close(); //*********notice this new line. result
//needs to be closed before calling another query
$sql="SELECT id FROM mytable";
$result2=$conn->query($sql);
echo $result2->num_rows; // **this does work because previous result
// was closed.
If you need to do multiple queries at once or need to do a query before you finish outputting rows for the previous one, use multi query. I use multi query for the second reason, getting another query before outputting all the rows of the previous one. This is important for nested queries, such as one in the middle of another, such as in multiple nested threads in a forum, or for nested replies used on some web pages.
Here is an example of one query done in the middle of another query.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM mytable";
$conn->multi_query($sql);
$result=$conn->store_result();
$count=0;
while($row = $result->fetch_assoc()) {
echo "$result['id'] $result['name'];
if ($count==0) {
// now you can do another query in the middle of this one
$sql="SELECT id FROM mytable";
$conn->multi_query($sql);
$result2=$conn->store_result();
$row2=$result2->fetch_assoc();
echo "result of second query is: $row2['id'] $row2['name']";
}
$count=$count+1;
}

Mysql Multiple PHP Queries, Skipped

If i'm doing multiple mysql queries on the same table, occasionally some get skipped.
Why is that?
For example:
<?php
mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'");
mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'");
mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'");
?>
Sometimes one of the queries will not be executed?
Why is that?
-Or is it something wrong with my server not general mysql?
(Obviously I know now to update the same table in the same query, but before that I was very confused as to why it happens, can anyone please explain?)
Thanks!
You do not need to make 3 queries, if you are updating the same rows:
$q = "
UPDATE table
SET field = '',
field2 = '',
field3 = 0
WHERE Id = :id
";
$statement = $pdo->prepare( $q );
$statement->bindParam(':id', $something, PDO::PARAM_INT);
$statement->execute();
Also, you should stop using the ancient mysql_* functions. They are not maintained anymore and process for deprecation has already begun.
Maybe you should avoid the 10+ year old API and learn something for this decade: PDO Tutorial for MySQL Developers.
debug your code to see if a query fails:
$result = mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Use the following to debug the code:
mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'") or die(mysql_error());
mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'") or die(mysql_error());
mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'") or die(mysql_error());
UPDATE
Make sure you are escaping $something using:
$something = mysql_real_escape_string($something);

Categories