Error in PHP & MySQL query - php

I'm trying to make query with a variable which represents the users.
This is the query:
$sq12 = "select sum(monto) from pagos where usuario = $_SESSION['XUSUARIO']" or die(mysql_error());
$re2 = mysql_query($sq12,$conexion);
$_SESSION['XUSUARIO'] is the data of each user to lookup in the db.
Edit:
I changed the query as requested, now it says ARRAY.

or die() is in the wrong place.
$sq12 ="select sum(monto) from pagos where usuario = {$_SESSION['XUSUARIO']}";
$re2 = mysql_query($sq12,$conexion) or die(mysql_error());

You can only interpolate scalar values into a string. To use an array of ids for example, use implode (or the alias join):
<?php
$usuario = implode(',',$_SESSION['XUSUARIO']);
$sq12 = "select sum(monto) from pagos where usuario in ($usuario)";
$re2 = mysql_query($sq12,$conexion) or die(mysql_error());
EDIT: PDO PDO PDO PDO

$_SESSION['XUSUARIO'] is an array, you will need to format it into a string for the query, doing something like this:
$string = '(';
$string .= implode(',', $_SESSION['XUSUARIO']);
$string .= ')';
And then add it into the query:
"... where usuario IN $string"

Related

php/sql AND statement not working

I have my code:
$db_date2;
$today2 = date("Y-m-d");
$sql1 = "SELECT * FROM todays_spend WHERE id =$user_id_session AND date=$today2";
$date_records = mysql_query($sql1);
while($today_trip=mysql_fetch_assoc($date_records)){
$db_date2 = $today_trip['date'];
}
echo $db_date2;
It is saying "Undefined variable: db_date2". When I remove the AND statement it works. Am I doing the AND statement wrong? the 'date' field in my database is also saved in the format Y-m-d.
also tried the single qoutes '' around the variables, still not working!
Actually it is using your variables as string in the query rather than their values so Just replace your code with the following:
$db_date2;
$today2 = date("Y-m-d");
$sql1 =
$sql1 = "SELECT * FROM todays_spend WHERE id ='".$user_id_session."' AND date='".$today2."'";
$date_records = mysql_query($sql1);
while($today_trip=mysql_fetch_assoc($date_records)){
$db_date2 = $today_trip['date'];
}
echo $db_date2;
For your variables, you'll need single quotes:
This:
$sql1 = "SELECT * FROM todays_spend WHERE id =$user_id_session AND date=$today2";
Should be:
$sql1 = "SELECT * FROM todays_spend WHERE id ='$user_id_session' AND date='$today2'";
You need to write single quote'' around your variable.
Write your query as below:-
$sql1 = "SELECT * FROM todays_spend WHERE id ='$user_id_session' AND date='$today2'";
Warning
mysql_* was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used
Hope it will help you :-)

Print sql query on localhost

I have a SQL query in my PHP file that makes use of some variables in it. I want to print the query itself on the localhost to check as to whether the entire query is been executed or not.
My query is like this:
$result = mysql_query("SELECT * FROM sample WHERE col01 LIKE '%$abc%',$db);
I am trying to print the query using echo $result but get Resource id #25 on localhost. I want to print Select * FROM ... as the output. Is there any way?
First of all: You are missing a double quote: $result = mysql_query("SELECT * FROM sample WHERE col01 LIKE '%$abc%'",$db).
That said, what stops you from
$sql="SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
$result = mysql_query($sql,$db);
echo $sql;
If you were using PDO (and you should, the old mysql_ functions are deprecated and insecure) you could just use PDOStatement->queryString property to view the query at a later time.
Store as a variable $sql
Its normal, first you need to fetch that resource obj
And anyway you missing a double quote,
example.
$sql = "SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
$result = mysql_query($sql);
while ($line = mysql_fetch_object($result)) {
echo $line->colname ."\n";
}
echo "\n" . ' query: ' . $sql
And from PHP 5.5.0 and beyond use mysqli
$sql = "SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
if ($result = $mysqliobj->query($sql)) {
while($line= $result->fetch_object()){
echo = $line->colname ."\n";
}
}
echo "\n" . ' query: ' . $sql
or print_r($mysqliobj->info); # store las query

How to take value from array into integer (PHP)

Input :
$sql1 = "SELECT COUNT(*) FROM matchTrip where userTripId = :tripId";
$stmt1 = $this->db->prepare($sql1);
$stmt1->bindParam(':tripId', $trip, PDO::PARAM_INT);
$temp = $stmt1->fetchObject();
echo(json_encode($temp));
Output:
How to take value from array :
of which json_encode looks like this: {"COUNT(*)":"7"}
Any help will be appreciated.
Why don't you just give the column an alias in the SQL itself?
$sql1 = "SELECT COUNT(*) as myCount FROM matchTrip where userTripId = :tripId";
Makes the rest easier to work with.
Do you mean json_decode? You can just put it between quotes and it should work; $array["COUNT(*)"].
But you can also add "AS myCount" to your SQL.
if to get rid of all the useless stuff from your code
$sql = "SELECT COUNT(*) FROM matchTrip where userTripId = ?";
$stmt = $this->db->prepare($sql);
$stmt->execute(array($table_of_user[$i]));
$count = $stmt->fetchColumn();
echo $count;
So why not just fecth as array?
$temp = $stmt1->fetch(PDO::FETCH_ASSOC);
echo $temp['COUNT(*)'];
Just use like this:
$json = json_encode($temp);
echo $json->{'COUNT(*)'}; // 7

PHP + convert array for use with IN statement

Lets say I want to send an email to the people who like big sized candy.
When I do this:
$query1 = mysql_query("SELECT id_candy FROM `candylist` WHERE
candysize > 100") or die(mysql_error());
$result = mysql_fetch_array( $query1 );
$query2 = mysql_query("SELECT mail FROM `buyers` WHERE
candysizeinterest IN ($result)
") or die(mysql_error());
This query2 is of course the issue.
$result is not in a proper format to be used and then I get the obvious error of:
**Unknown column 'Array' in 'where clause'**
I need help to format the results of the query in a way that it looks like:
($val1, $val2, $val3....and so on)
Then I will be able to use it for an IN statement.
But I just do not know how to do so.
Try
$array = array();
while($result = mysql_fetch_array( $query1 ))
{
$array[] = $result['id_candy'];
}
Then use implode
$in_condition = implode(',', $array);
At last
$query2 = mysql_query("SELECT mail FROM `buyers` WHERE candysizeinterest IN ($in_condition)
NOTE : please switch to PDO or mysqli_*
you have a mistake in your sintax of $query2 you place array instead of actual value
change
$query2 = mysql_query("SELECT mail FROM `buyers` WHERE candysizeinterest IN ($result)
to
$query2 = mysql_query("SELECT `mail` FROM `buyers` WHERE `candysizeinterest` IN ('".$result['id_candy']."')");
I would like to also to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO for new projects.
You can use implode() to turn your array into a comma separated string:
implode(',',$result);
You can use that with IN
To convery an array to a comma sepearted string you would use
implode (",",$array)

MYSQL formulating a search query

I'm having slight difficulties (syntax presumably) formulating a query for a search I'm writing in php.
So far I have this:
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
trimmed is defined as
$trimmed = trim($var);
What I'm trying to accomplish is, use that query to search for a certain row in my mysql database. I've confirmed that it does indeed connect to the dbase and it does grab data from the table. I'm 99% new to php and mysql, I've just started working on this. Any help would be greatly appreciated.
EDIT: Oh I use the query here:
$result = mysql_query($query); I'm sure the issue isn't here, but in $query
Change
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
to
$query = "SELECT * FROM $table WHERE $field LIKE '$trimmed'";
It's always a good idea to escape any special characters, such as backslash, in the input. With mysql, you can use mysql_escape_string:
$trimmed = mysql_escape_string($trimmed);
$query = "SELECT * FROM $table WHERE $field LIKE '$trimmed'";
Equivalent commands exist in mysqli, PDO, and all PHP frameworks.
Check out the PHP manul, example:
$query= mysql_query("SELECT data FROM mydb;");
$myarray= array();
while ($row= mysql_fetch_array($query)) {
$myarray[] = $row['data'];
}
EDIT
This is your code? if so, you have a syntax error:
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
should be:
$query = ("SELECT * FROM $table WHERE $field LIKE '$trimmed'");

Categories