I have a simple SELECT statement:
$sql = "SELECT count(*) FROM member_temp WHERE member_Id = '".trim($id)."'";
The member_Id column is a VARCHAR(25) NOT NULL
This works fine until the SELECT gets to a member_Id that has a alpha value behind it, like 1126A. It then throws the error
Could not prepare SQL statement:SELECT count(*) FROM member_temp WHERE member_Id = '1126A'
As a test I remove this record and the SELECT runs fine until the next value with an A.
How can I make this query run and process records with an alpha character?
This is part of larger block of code that deletes records not found from the main member table:
while ( #data = $sth->fetchrow_array() ) {
my $id = $data[2];
my $pk = $data[0];
$sql = "SELECT count(*) FROM member_temp WHERE member_Id = '" . trim($id) . "'";
#print "$sql\n";
my $xth = $dbh->prepare($sql);
$xth->execute();
$cRows = $xth->fetchrow_array() || die "Could not prepare SQL statement:$sql";
#print "$cRows\n";
if ( $cRows == 0 ) {
$sql = "DELETE FROM member WHERE sys_Id = " . $pk;
$xth = $dbh->prepare($sql);
$xth->execute();
$cnt_del++;
}
Ok, this is Perl answer now :)
There is nothing wrong with your query (except that it is not preparing statements correctly and you are using string interpolation).
In the comments you said if this query is run directly
It completes successfully and returns a value of 0
Then in your code you have one condition which is wrong
$cRows = $xth->fetchrow_array() || die "Could not prepare SQL statement:$sql";
That means even if the query executed correctly but has 0 rows, it should show you that error message, which is not right.
So all you need to do is to fix that error message. That die should be shown if the query failed to execute, not when it executed correctly but has no results.
You can correct your query like
$sql = "SELECT count(*) FROM member_temp WHERE member_Id = ?";
$xth = $dbh->prepare($sql);
$xth->execute($id) or die("Failed to execute query:". $xth->errstr);
And your rows check can be
if ($xth->rows == 0)
// No match found
Related
I have the following code, which generates DQL queries.
When I echo my $dql and copy paste it into phpmyadmin and execute it, it works perfectly, but when trying to execute it with Doctrine I keep running into "'[Syntax Error] line 0, col 6981: Error: Unexpected 'WHERE'" error. What am I doing wrong?
$dqlStaticPartial = $dql = "UPDATE \VendorName\MyBundle\Entity\Product cp SET cp.guide_number = CASE ";
$uniqueIds = [];
$i = 0;
foreach($result as $row){
$guideNumber = $this->generateGuideNumber($param1, $param2);
$dql .= "WHEN cp.uniqid = '".$row['uniqid']."' THEN '$guideNumber' ";
$uniqueIds[] = "'".$row['uniqid']."'";
$i++;
if($i % 100 === 0){
$dql .= " END WHERE uniqid IN (".implode(',', $uniqueIds).")";
$this->entityManager->createQuery($dql)->execute();
$dql = $dqlStaticPartial;
}
}
(I know, this is not okay, i'm going to put this in a transaction and I will execute the query after every 100th iteration and I'm gonna escape inputs etc...first I want my query to work)
My guess is that you have more then 100 records and if that is the case then one of the problems you're creating is that your query ends up like this:
UPDATE cp SET cp.guide_number = CASE
WHEN cp.uniqid = '1' THEN '1234'
-- more rows ...
WHEN cp.uniqid = '99' THEN '4563'
END
WHERE uniqid IN (1,...,99)
WHEN cp.uniqid = '100' THEN '1234'
-- more rows ...
WHEN cp.uniqid = '199' THEN '4563'
END
WHERE uniqid IN (100,...,199)
etc. etc.
You should clear the allready executed part of your query and then restart building up your query once you reach ($i % 100 === 0)
I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle
Low level question but, I understand that you can select elements from a table using:
$sql = "SELECT blah FROM TABLE WHERE this = 'something' ";
But when I try to select a specific value from my table, where let's say a user has no tries left so if I try to grab how many tries they have left with:
$sql = "SELECT tries FROM table WHERE user = 'something'";
How would I grab that value specifically if it was 5 or 9? I tried setting a variable equal to something I $sql off my table but it doesn't grab the value.
Edit
I have a database that has a table called Item which contains: id, name, value, and stock of a particular item. If a user wants to order that item I will first check it if's in stock with a function, to see if it is not in stock then a error message is printed, otherwise accept the order.
Extremely primitive since I'm just trying to get grab the stock value first.
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' .$query.''; //test purposes
$mysql_handle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error connecting to database server");
mysql_select_db($dbname, $mysql_handle)
or die("Error selecting database: $dbname");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
echo '' .$sql2. ''; //test purposes
whats the correct way to assign the value from that specific stock to a variable?
If you want to grab rows with a set of possible values you can use 'IN' such as:
Get all columns from users table where users have 5 or 9 tries:
SELECT * FROM users WHERE tries IN('5', '9'); or
If you want to select where the user has no tries left, assuming the tries column is a numeric type you can look for rows with 0 tries:
Get all columns from Item table where stock is 0:
SELECT * FROM db_inv.Item WHERE stock = '0';
Get all columns from users table where tries is 0:
SELECT * FROM users WHERE tries = '0';
As for your php code you should be able to do the following:
$query = $_GET['query']; //id I get from the specified item
echo 'the id is: ' . $query; //test purposes
$mysql_handle = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Error connecting to database server");
$sql1 = "SELECT item_stock FROM chat-db.Item WHERE id = '".$query."'";
$results = mysqli_query($mysql_handle, $sql1);
if (!empty($results) && mysqli_num_rows($results) > 0) {
while($rec = mysqli_fetch_array($results)) {
echo $rec['item_stock'];
}
}
I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";
My mysql query is working fine
INSERT INTO donor_location (pc_id)
SELECT id
FROM pc
WHERE postcode= ?
i.e gets the postcode id from a postcode table then inserts that id into donor_location table.
I am using mysqli and prepared statements
without the select part it would be quite easy - something like
$stmt = $mysqli->prepare("INSERT INTO donor_charity(
id) values (?)") ;
however I am completely lost about how to incorporate the select
What you do is almost the same, just changing the query bit.
To select all records from charity_donor where the id is 25, you would do the follwing query:
SELECT *
FROM donor_charity
WHERE id = 25
Now to query this, first you have to prepare it:
$stmt = $mysqli->prepare("
SELECT *
FROM donor_charity
WHERE id = ?
");
Now to loop over the results, you must bind the param, and execute the query.
$stmt->bind_param('d', 25 ); // First param means the type of the value you're
passing. In this example, d for digit.
$stmt->execute();
Then you setup an array to hold the data returned from the query,
$row = array();
stmt_bind_assoc($stmt, $row);
And now to loop over the returned data.
while ( $stmt->fetch () ) {
print_r($row); // Should now contain the column.
}
For documentation, see:
Prepare: http://www.php.net/manual/en/mysqli.prepare.php
Bind param: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Execute: http://www.php.net/manual/en/mysqli-stmt.execute.php
Fetch: http://www.php.net/manual/en/mysqli-stmt.fetch.php
You need to use Bind_param after Prepare statement.
$sql = "INSERT INTO donor_charity(
id) values (?)
";
/* create a prepared statement */
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
/* bind parameters for markers */
$stmt->bind_param('ssssss', $id);
$id = '123456';
/* execute query */
$stmt->execute();
Hope this post helps, it's so simple.
http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertRecordsUsingPreparedStatement.htm