updating mysql database with php variable - php

I want to update my mysql database, using php using variable method but it is not updating. I don't know what the problem is. This is my code:
$result = mysql_query("SELECT * FROM total") or die(mysql_error());
$i=$row['number'];
$n=$i+1;
$result = mysql_query("UPDATE total SET number = " . $n . " WHERE number = " . $i . "") or die(mysql_error());
How can I update my mysql database using php?

You can increment the column_value like this column_name = column_name + 1 without using SELECT.
UPDATE total SET number = number + 1

It can be just with SQL without need of select. When it is not required don't use php. What can be done in mysql should be done in mysql. It's faster.
UPDATE `total` SET number = number + 1;
Moreover, you should read the red box on mysql_* documentation. These functions are depracated and will be removed in future. Consider using MYSQLI or PDO

your query syntax is wrong, try this,
$result = mysql_query("UPDATE total SET number = '" . $n . "' WHERE number = '" . $i . "'");

The syntax fo your query is wrong it should be
UPDATE `total` SET number = number + 1;
you have done
UPDATE `total` S number = number + 1;
refer this mysql doc

Related

PHP + MySQL "WHERE ... IN" doesn't work

I build my query like this:
foreach($ids as $key => $idi) {
$ids[$key] = "'" . $idi . "'";
};
$ids_imploded = implode(", ", $ids);
$sql = "SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN (" . $ids_imploded . ") AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT " . count($ids) . ";";
$result = mysqli_query($con, $sql);
Where $ids is just array of few numbers (so the $ids_imploded = "'132', '165'").
When I run the generated query in phpMyAdmin, I get what I want. When I run it from PHP, it returns just object with nulls. Why?
I doesn't work neither if I remove the escaping loop.
EDIT: generated query is echoed like
SELECT record_id, email FROM `actions_attendees` WHERE `action_id` IN ('1614', '1615') AND `backup` = 1 ORDER BY `timestamp` ASC LIMIT 2;
The problem could be that you are querying the wrong database, try select a db first, try executing this before the query :
mysql_select_db('yourdb');
Is the result of your query true ? Check your connection object, it seems like you are not on the right database.
It appears that the query was indeed working even in PHP, but later when I was processing the results, intellisense tricked me and I was using mysql_fetch_assoc instead of mysqli_fetch_assoc...

Selecting MySQL query via PHP variables

I am getting zero in $booked_num, I tried the query in SQL with values in place of variables, it worked fine. But I don't know where I am making a mistake, please help.
I already echoed every variable and everything is fine, but nothing is there in $booked_rowand $booked_num is echoing zero.
require_once 'mysql_connector.php';
$booked_result = mysql_query('select * from booked where train_no = ".$train_no." and date = ".$date." and st_from = ".$st_from." and st_to = ".$st_to.";') or die(mysql_error()) ;
$booked_num = mysql_num_rows($booked_result);
echo $booked_num;
$booked_row = mysql_fetch_array($booked_result,MYSQL_ASSOC);
print_r($booked_row);
$booked_result = mysql_query('select * from booked where train_no = ".$train_no." and date = ".$date." and st_from = ".$st_from." and st_to = ".$st_to.";') or die(mysql_error()) ;
This syntax is incorrect - you need to close the string before concatenating variables.
Something like:
$booked_result = mysql_query('select * from booked where train_no = "' .$train_no. '" and date = "' .$date. '" and st_from = "' .$st_from. '" and st_to = "' .$st_to. '";') or die(mysql_error());
Also, you should consider switching to the PDO library. Among other things, it will help you avoid sql injection attacks in your queries.

Using PHP to pull data from MySQL table column randomly

I am using the following (assume I already plan to change these to mysqli at a later date and am aware of the insecurity of the queries used), to pull text strings from rows in one column in a MySQL table and the output in a browser would, ideally, be a randomly selected string from this column:
mysql_connect($host,$username,$password);
mysql_select_db($database) or die(mysql_error ());
$query="SELECT * FROM `tablename` ORDER BY RAND() LIMIT 0,1;";
$result=mysql_query($query);
$rows = array();
while($row = mysql_fetch_array($rs)) {
$rows[] = $row;
}
mysql_close();
$max = count($rows) - 1;
Using the following echo line to achieve the last bit in the browser:
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4]$
?>
I receive the error "PHP Notice: Undefined offset: 0 in script.php on line 19" in reference to this echo line (which, admittedly, was pieced together from other threads and tutorials, so I do not follow completely), however, I've since resolved all other errors logged and observed, so if possible, how can I amend this so the output is just a single row (the text within it) from the column?
Faster and better than using RAND()
$conn = mysqli_connect($host,$username,$password, $database);
if($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$total_rows = 20; //Generate Random number. You could get $total_rows with a first query counting all rows.
$selected_row = mt_rand(0, $total_rows);
//$selected_row -= 1; //just in case you randomized 1 - $total_rows and still need first row.
//Use the result in your limit.
$query="SELECT * FROM `tablename` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["columnname"];
}
Edit it from mysql to mysqli (on the fly). You would not want to use RAND() if your table is very large. Believe me!
In your SELECT-statement, you are telling the database to order the strings randomly. So just get the first one and echo it:
$row = mysql_fetch_array($rs)
echo $row['name_of_field_you_want_to_echo'];
You never define the variable $rs. Other than that...
If you are selecting the first items from a SQL query, you don't need to specify both the limit and top.
$result = mysql_query("SELECT * FROM `tablename` ORDER BY RAND() LIMIT 1");
Since that will ever return one row, you can use mysql_fetch_row
$row = mysql_fetch_row($result);
and then you can get the field from that row with
echo $row["column_name"];

using a php variable in the WHERE clause of a mysql query

I'm running a very simple query that I think should work. The only thing that I haven't done before is put a php variable in the WHERE clause of the query. The variable $X is a numerical value, say 100. When I run this query, I just get a value of 0 returned. Am I doing something obviously stupid?
SELECT generator_64k.n
FROM generator_64k
WHERE generator_64k.n<= '$X'
I've looked around the web and also tried this:
SELECT generator_64k.n
FROM generator_64k
WHERE generator_64k.n<= '" . $X . "'
But this also just returns 0.
Any ideas? Thanks in advance.
$query = "SELECT generator_64k.n FROM generator_64k WHERE generator_64k.n<= {$X};";
Try this one, or post your PHP code.
<?php
$X = 100;
$query = "SELECT n FROM generator_64k WHERE n <= $X";
$result = mysql_query($query);
if (!$result) {
echo ('Query error: ' . mysql_error());
}
E.g of php and using variables
$query = "select * from table1 where col1 <=" .$myVariable;
$result= mysql_query($query);
The mysql_query() function returns false on error (false == 0), otherwise, it returns a resource. mysql_query does not return the value from the result set. You must use mysql_fetch_assoc or something similar to fetch the rows from the result set.
Also, ensure that you wrap the query in double quotes so PHP can expand the variable $X.
Use mysql_error to fetch the error from the last call to mysql_query.
make it like this
$sql="select `username` from `users` where id='$newid';";
mysql_query($sql);
here $newid is the int value.
The symbol used before and after username, to get this you have to press the key just below esc .
You can't have ' around your numeric value. MySQL will treat it as string.
You should do this instead
" WHERE number <= " . (int)$val . " .. "
// or (but not recommended due to security problem)
" WHERE number <= $val "

Storing&Retrieving Integer in/from MySQL Database

I have a problem with integers in MySQL. I am trying to update a cell which stores an integer. However, I have problem with the type of that cell. Actually it is type is set to int but when I retrive the data I always get 0 and I belive it is because of the problem about how I am trying to get it. Here is my code sample;
function updateNumb($username) {
$query = "SELECT `num` FROM `profiles` WHERE `nick`='" . $username . "'";
$result = mysql_query($query, $this->conn) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$row['num'] = $row['num'] + 1;
$numb = (int)$row['num'] + 1;
//here I update the data.
$query = "UPDATE `profiles` SET `num`=" . $numb . " WHERE `nick`='".$username."'";
mysql_query($query, $this->conn) or die(mysql_error());
return $numb;
}
Can it be because of mysql_fetch_array stuff? Or how could I overcome this problem?
replace partisayisi with num
There is nothing wrong with the code you provided, maybe it's not doing what you really need, for example num is incremented twice, but there are no visible mistakes that would make it return 0, at least not in what we can see.
Make sure you provide valid username, try to echo your query before sending to mysql to see what it really looks like, maybe try this query yourself in mysql client or phpmyadmin to see what's going on.
Also if the only thing you need is to increment num for some user you can do it in one update, you don't need to use select to get that number:
UPDATE profiles set num=num+1 WHERE nick='somenick'

Categories